2

我有一个服务器,它期望 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);
4

2 回答 2

1

HttpClient 根据所附消息实体的属性和实际协议设置自动生成Content-LengthTransfer-Encoding头值。

不要手动设置这些标题。

于 2019-11-05T09:17:47.090 回答
0

尝试:

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

这会将内容长度设置为 0。

于 2013-07-31T15:13:07.613 回答