我有一台服务器,希望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()设置内容长度,这会引发错误,说明内容已经存在)
这是我用来创建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 :(得分:0)
尝试:
httppost.setHeader(HTTP.CONTENT_LEN,"0");
这会将内容长度设置为0。
答案 1 :(得分:0)
HttpClient根据附带的消息实体的属性和实际的协议设置自动生成Content-Length
和Transfer-Encoding
标头值。
请勿手动设置这些标题。