From cab08187b3e6f334f6032dcc7ccf73aaeb1ca39a Mon Sep 17 00:00:00 2001 From: Benjamin Bargeton Date: Mon, 22 Apr 2024 15:12:17 +0200 Subject: [PATCH] Only copy body request content if body is present This avoids to have a "Transfer-Encoding: chunked" with an empty body if downstream exchanges are negotiated in HTTP 1.1 Fixes gh-3325 --- .../mvc/handler/RestClientProxyExchange.java | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/handler/RestClientProxyExchange.java b/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/handler/RestClientProxyExchange.java index 1f24992472..ed01565423 100644 --- a/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/handler/RestClientProxyExchange.java +++ b/spring-cloud-gateway-server-mvc/src/main/java/org/springframework/cloud/gateway/server/mvc/handler/RestClientProxyExchange.java @@ -18,6 +18,7 @@ import java.io.IOException; import java.io.OutputStream; +import java.io.UncheckedIOException; import org.springframework.http.client.ClientHttpResponse; import org.springframework.util.StreamUtils; @@ -34,10 +35,21 @@ public RestClientProxyExchange(RestClient restClient) { @Override public ServerResponse exchange(Request request) { - return restClient.method(request.getMethod()).uri(request.getUri()) - .headers(httpHeaders -> httpHeaders.putAll(request.getHeaders())) - .body(outputStream -> copyBody(request, outputStream)) - .exchange((clientRequest, clientResponse) -> doExchange(request, clientResponse), false); + var requestSpec = restClient.method(request.getMethod()).uri(request.getUri()) + .headers(httpHeaders -> httpHeaders.putAll(request.getHeaders())); + if (isBodyPresent(request)) { + requestSpec.body(outputStream -> copyBody(request, outputStream)); + } + return requestSpec.exchange((clientRequest, clientResponse) -> doExchange(request, clientResponse), false); + } + + private static boolean isBodyPresent(Request request) { + try { + return request.getServerRequest().servletRequest().getInputStream().available() > 0; + } + catch (IOException e) { + throw new UncheckedIOException(e); + } } private static int copyBody(Request request, OutputStream outputStream) throws IOException {