2013-04-10 40 views
1

我有一个服务器期望Content-Length作为POST标题的一部分。对于POSTing,我使用的是Apache HttpComponents库。如何将Content-Length头添加到Apache HttpComponents中的HttpPost?

这是预期的请求的一个精简版(具有所有所需要头ofcourse):

POST /ParlayREST/1.0/sample/ HTTP/1.1 
Content-Type: application/json 
Accept: application/json 
Host: server.url.com:8080 
Content-Length: 287 
{ 
    "listenerURL":"http://application.example.com/notifyURL"}, 
    "sessionId":"12345" 
} 

我已经使用的HttpPostsetEntity方法来设置StringEntity(换算json - > String - > StringEntity)作为POST的内容。但是当我执行这个请求时,我最终得到一个POST请求,它在它的头部中没有指定内容长度

无论如何添加这个缺失的标题?

(我想的setHeader()设置的Content-Length这引发了错误说,内容长度已经存在)

这是我使用来创建POST请求的代码:

//Convert the registration request object to json 
StringEntity registrationRequest_json_entity = new StringEntity(gsonHandle.toJson(registrationRequest)); 
registrationRequest_json_entity.setContentType("application/json"); 

//Creating the HttpPost object which contains the endpoint URI 
HttpPost httpPost = new HttpPost(Constants.CLIENT_REGISTRATION_URL); 
httpPost.setHeader(HTTP.CONTENT_TYPE,"application/json"); 
httpPost.setHeader("Accept","application/json"); 
httpPost.setHeader(HTTP.TARGET_HOST,Constants.REGISTRATION_HOST + ":" + Constants.REGISTRATION_PORT); 

//Set the content as enitity within the HttpPost object  
httpPost.setEntity(registrationRequest_json_entity); 

HttpResponse response = httpClient.execute(httpPost, new BasicHttpContext()); 
HttpEntity entity = response.getEntity(); 
if (entity != null) { 
    //work on the response 
} 
EntityUtils.consume(entity); 
+0

您可以添加用于创建请求的代码吗? – vptheron 2013-04-10 13:18:51

+0

当然..将更新与我的代码帖子 – user2265993 2013-04-11 06:51:25

+0

你如何确定'Content-Length'头没有被发送? – Perception 2013-04-19 05:03:04

回答

0

尝试:

httppost.setHeader(HTTP.CONTENT_LEN,"0"); 

这将设置共同潜在长度为0.

相关问题