2016-01-25 40 views
2

對不起,如果問題可能重複。我不熟悉Java和我被困了科爾多瓦插件,返回頭在非JSON結構,我認爲這是如何將HTTP請求的標題添加到回覆中

//These parts works fine returning response body 

HttpRequest request = HttpRequest.post(this.getUrlString()); 
this.setupSecurity(request); 
request.headers(this.getHeaders()); 
request.acceptJson(); 
request.contentType(HttpRequest.CONTENT_TYPE_JSON); 
request.send(getJsonObject().toString()); 
int code = request.code(); 
String body = request.body(CHARSET); 
JSONObject response = new JSONObject(); 
response.put("status", code); 

// in this line I must put JSON converted headers instead of request.headers() 
response.put("headers", request.headers()); 

我試過request.headers()的Map.soString()呈現

String headers = request.headers().toString(); 

JSONObject headers = new JSONObject(request.headers()); 

上述線改變爲

response.put("headers", headers); 

但他們都沒有工作。
我應該如何將JSON作爲響應發送給JSON?

更多背景:
目前的響應頭:

{ 
    null=[HTTP/1.0 200 OK], 
    Content-Type=[application/json], 
    Date=[Mon, 25 Jan 2016 07:47:31 GMT], 
    Server=[WSGIServer/0.1 Python/2.7.6], 
    Set-Cookie=[csrftoken=tehrIvP7gXzfY3F9CWrjbLXb2uGdwACn; expires=Mon, 23-Jan-2017 07:47:31 GMT; Max-Age=31449600; Path=/, sessionid=iuza9r2wm3zbn07aa2mltbv247ipwfbs; expires=Mon, 08-Feb-2016 07:47:31 GMT; httponly; Max-Age=1209600; Path=/], 
    Vary=[Accept, Cookie], 
    X-Android-Received-Millis=[1453708294595], 
    X-Android-Sent-Millis=[1453708294184], X-Frame-Options=[SAMEORIGIN] 
} 

和響應的身體被髮送。所以我需要解析它們,但我做不到。

+0

你看過什麼標題實際上是?你是什​​麼意思「它不起作用?」 – matt

+1

標題不必轉換爲JSON,您必須將它們添加到HttpResponse對象 –

+0

爲什麼不能解析標題? – usr2564301

回答

1

應該是做到這一點的方式:

JSONObject headers = new JSONObject(request.headers()); 

然而,頭部的「的toString()」顯示似乎顯示了與null鍵映射條目。這在JSON中不起作用:JSON對象屬性名稱不能爲null。我的猜測是null關鍵造成了這次事故。

所以我認爲你需要篩選出「壞」的條目;即代碼是這樣的:

JSONObject headers = new JSONObject() 
for (Map.Entry entry: request.headers().entries()) { 
    if (entry.getKey() != null) { 
     headers.put(entry.getKey(), entry.getValue()); 
    } 
} 
相關問題