【问题标题】:How do I add Content-Length header to HttpPost within Apache HttpComponents?如何在 Apache HttpComponents 中将 Content-Length 标头添加到 HttpPost?
【发布时间】:2013-04-10 12:35:47
【问题描述】:

我有一个服务器,它期望 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"
}

我已使用 HttpPostsetEntity 方法将 StringEntity(转换后的 json -> String -> StringEntity)设置为邮政。但是当我执行请求时,我最终得到了一个 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);

【问题讨论】:

  • 您可以添加用于创建请求的代码吗?
  • 当然..会用我的代码更新帖子
  • 您如何确定Content-Length 标头没有被发送?

标签: java http-post apache-httpcomponents content-length


【解决方案1】:

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

不要手动设置这些标题。

【讨论】:

    【解决方案2】:

    试试:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多