Add missing "Content-Length: 0" header with HttpComponents

Prior to this commit, HTTP requests sent with the
`HttpComponentsClientHttpRequestFactory` would not set a
"Content-Length" header for empty request bodies. Setting a request
entity is the expected behavior for unsafe HTTP methods, and this would
align the behavior with other HTTP clients.
Developers would often rely on `BufferingClientHttpRequestFactory` to
set this information on the request.

This commit ensures that a `NullEntity` is used for unsafe HTTP methods,
when no body has been set for the request. This result in a
"Content-Length:0" request header.

Fixes gh-32678
This commit is contained in:
Brian Clozel
2024-05-02 15:42:35 +02:00
parent 5a24e94d2e
commit 47c5cd208c
3 changed files with 48 additions and 3 deletions

View File

@@ -30,6 +30,8 @@ import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.Method;
import org.apache.hc.core5.http.io.entity.NullEntity;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.springframework.http.HttpHeaders;
@@ -89,8 +91,10 @@ final class HttpComponentsClientHttpRequest extends AbstractStreamingClientHttpR
addHeaders(this.httpRequest, headers);
if (body != null) {
HttpEntity requestEntity = new BodyEntity(headers, body);
this.httpRequest.setEntity(requestEntity);
this.httpRequest.setEntity(new BodyEntity(headers, body));
}
else if (!Method.isSafe(this.httpRequest.getMethod())) {
this.httpRequest.setEntity(NullEntity.INSTANCE);
}
ClassicHttpResponse httpResponse = this.httpClient.executeOpen(null, this.httpRequest, this.httpContext);
return new HttpComponentsClientHttpResponse(httpResponse);