Skip to content

Commit aca2649

Browse files
imzhoukunqiangbclozel
authored andcommitted
Update Content-Length if body changed by client interceptor
Prior to this commit, the HTTP interceptor model used for `RestTemplate` and `RestClient` would not update the "Content-Length" request header, even when the request body had been updated by a `ClientHttpRequestInterceptor`. Even though this is the `ClientHttpRequestInterceptor`'s responsibility (along with the content type and encoding changes if needed), this would result in invalid requests. This invalid situation can be detected by `InterceptingClientHttpRequest`. This commit ensures that such situations are detected and fixed automatically by setting the Content-Length header to the actual body size, right before executing the actual request, after all interceptors are done. Closes gh-33459
1 parent be5d5fa commit aca2649

File tree

2 files changed

+5
-0
lines changed

2 files changed

+5
-0
lines changed

spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,10 @@ public ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOExc
9393
request.getHeaders().forEach((key, value) -> delegate.getHeaders().addAll(key, value));
9494
request.getAttributes().forEach((key, value) -> delegate.getAttributes().put(key, value));
9595
if (body.length > 0) {
96+
long contentLength = delegate.getHeaders().getContentLength();
97+
if (contentLength > -1 && contentLength != body.length) {
98+
delegate.getHeaders().setContentLength(body.length);
99+
}
96100
if (delegate instanceof StreamingHttpOutputMessage streamingOutputMessage) {
97101
streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
98102
@Override

spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ void changeBody() throws Exception {
204204
ClientHttpRequest request = requestFactory.createRequest(URI.create("https://example.com"), HttpMethod.GET);
205205
request.execute();
206206
assertThat(Arrays.equals(changedBody, requestMock.getBodyAsBytes())).isTrue();
207+
assertThat(requestMock.getHeaders().getContentLength()).isEqualTo(changedBody.length);
207208
}
208209

209210

0 commit comments

Comments
 (0)