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..31fa53a67f82 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 @@ -88,6 +88,16 @@ public ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOExc return nextInterceptor.intercept(request, body, this); } else { + + /* + * After intercepted by the interceptors, the length of the body may change. + * Set the latest body.length to "Content-Length" + */ + long contentLength = request.getHeaders().getContentLength(); + if (contentLength > -1 && contentLength != body.length) { + request.getHeaders().setContentLength(body.length); + } + HttpMethod method = request.getMethod(); ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), method); request.getHeaders().forEach((key, value) -> delegate.getHeaders().addAll(key, value)); 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..157c553f644e 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,9 @@ void changeBody() throws Exception { ClientHttpRequest request = requestFactory.createRequest(URI.create("https://example.com"), HttpMethod.GET); request.execute(); assertThat(Arrays.equals(changedBody, requestMock.getBodyAsBytes())).isTrue(); + + // When the request body is changed, the "Content-Length" in the request header also needs to be changed. + assertThat(requestMock.getHeaders().getContentLength()).isEqualTo(changedBody.length); }