Java Http - Post Header Content-Length

时间:2018-02-27 10:53:17

标签: java http

我的http-header有问题。 我需要发送一个空主体的后请求和标题“Content-Length:0”。但这似乎是不可能的,因为我得到了这个例外:

- org.apache.http.ProtocolException:已存在Content-Length标头 -

但是当我不包含标题时,请求中没有Content-Length标头,因此我得到400:Bad Request。 我也用Python构建它,并且它工作正常,但我不能使它在java中工作。你能帮帮我吗?

这是我的代码:

HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(header..);
httpPost.addHeader(another header);
httpPost.addHeader("Content-Type","application/xml");
httpPost.addHeader("Content-Length","0");
httpPost.addHeader(another header);
HttpResponse response = client.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode());

修改

解决了@Beno Arakelyan的回答问题。

2 个答案:

答案 0 :(得分:0)

您不需要计算内容长度,客户端会为您处理。请尝试删除标题并设置正文,例如:httpPost.setEntity(new StringEntity(""))

答案 1 :(得分:0)

我尝试使用基于apache http客户端的http-request发送Content-Length。它工作正常。例如:

private static final HttpRequest<?> HTTP_REQUEST =
      HttpRequestBuilder.createGet(YOUR_URI)
        .addDefaultHeader(HttpHeaders.CONTENT_LENGTH, "0")
        .build();

public void test(){
  System.out.println(HTTP_REQUEST.execute().getStatisCode()); // is 200
}
相关问题