我有一台服务器,它希望Content-Length作为POST标头的一部分。 对于POST,我使用Apache HttpComponents库。
这是预期请求的简化版本(带有所有必需的课程标头):
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"
}
我已经使用HttpPost的setEntity方法将StringEntity (转换为json- > String-> StringEntity)设置为POST的内容。 但是,当我执行请求时,我最终得到了一个POST请求,该请求未在其标头中指定Content-length 。
无论如何,有没有添加此丢失的标题?
(我尝试使用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);