httpclient: Content-Length header already present问题

现象:用httpclient发送http请求时,客户端返回:

org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:822)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
……
Caused by: org.apache.http.ProtocolException: Content-Length header already present
at org.apache.http.protocol.RequestContent.process(RequestContent.java:67)
at org.apache.http.protocol.ImmutableHttpProcessor.process(ImmutableHttpProcessor.java:108)
at org.apache.http.protocol.HttpRequestExecutor.preProcess(HttpRequestExecutor.java:174)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:462)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
... 27 more

原因:查看httpclient中RequestContent类的process方法,看到当body非空时,会自动加上Content-Length请求头及其对应值,不需要自己手动加上它。源码如下:

</pre>
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (request instanceof HttpEntityEnclosingRequest) {
if (request.containsHeader(HTTP.TRANSFER_ENCODING)) {
throw new ProtocolException("Transfer-encoding header already present");
}
if (request.containsHeader(HTTP.CONTENT_LEN)) {
throw new ProtocolException("Content-Length header already present");
}
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
if (entity == null) {
request.addHeader(HTTP.CONTENT_LEN, "0");
return;
}
// Must specify a transfer encoding or a content length
if (entity.isChunked() || entity.getContentLength() < 0) {
if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
throw new ProtocolException(
"Chunked transfer encoding not allowed for " + ver);
}
request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
} else {
request.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength()));
}
// Specify a content type if known
if (entity.getContentType() != null && !request.containsHeader(
HTTP.CONTENT_TYPE )) {
request.addHeader(entity.getContentType());
}
// Specify a content encoding if known
if (entity.getContentEncoding() != null && !request.containsHeader(
HTTP.CONTENT_ENCODING)) {
request.addHeader(entity.getContentEncoding());
}
}
}
解决方法:remove掉Content-Length后,不再抛异常,请求正常返回。

https://github.com/square/retrofit/issues/454

原文地址:https://www.cnblogs.com/timssd/p/5971702.html