diff --git a/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java index 07203df37102..84ee77f3d704 100644 --- a/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java @@ -93,6 +93,10 @@ public ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOExc request.getHeaders().forEach((key, value) -> delegate.getHeaders().addAll(key, value)); request.getAttributes().forEach((key, value) -> delegate.getAttributes().put(key, value)); if (body.length > 0) { + long contentLength = delegate.getHeaders().getContentLength(); + if (contentLength > -1 && contentLength != body.length) { + delegate.getHeaders().setContentLength(body.length); + } if (delegate instanceof StreamingHttpOutputMessage streamingOutputMessage) { streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() { @Override diff --git a/spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java index 2735c00e315f..f8248d0e0858 100644 --- a/spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java @@ -204,6 +204,7 @@ void changeBody() throws Exception { ClientHttpRequest request = requestFactory.createRequest(URI.create("https://example.com"), HttpMethod.GET); request.execute(); assertThat(Arrays.equals(changedBody, requestMock.getBodyAsBytes())).isTrue(); + assertThat(requestMock.getHeaders().getContentLength()).isEqualTo(changedBody.length); }