我的 http header 有问题。 我需要发送一个带有空正文和标题“Content-Length:0”的后请求。但这似乎不可能,因为我得到了这个异常:
--org.apache.http.ProtocolException:内容长度 header 已存在--
但是当我不包含 header 时,请求中没有 Content-Length header ,因此我得到 400:错误请求。 我也在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 的答案解决了问题。
最佳答案
我尝试使用 http-request 发送 Content-Length
它建立在 apache http 客户端之上。效果很好。示例:
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
}
关于Java Http - Post header 内容长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49006925/