2016-01-25 38 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()); 
    } 
} 
相关问题