我有一个服务器,期望Content-Length作为POST标题的一部分。对于POSTing,我使用的是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);
尝试:
httppost.setHeader(HTTP.CONTENT_LEN,"0");
这会将内容长度设置为0。