diff --git a/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java b/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java index d72efa9cbbf..64c5366fefd 100644 --- a/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java +++ b/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java @@ -360,8 +360,8 @@ final class DefaultRestClient implements RestClient { } @Override - public T exchange(ExchangeFunction exchangeFunction) { - return exchangeInternal(exchangeFunction, true); + public T exchange(ExchangeFunction exchangeFunction, boolean close) { + return exchangeInternal(exchangeFunction, close); } private T exchangeInternal(ExchangeFunction exchangeFunction, boolean close) { diff --git a/spring-web/src/main/java/org/springframework/web/client/RestClient.java b/spring-web/src/main/java/org/springframework/web/client/RestClient.java index 25c41bd0cb2..39a317044d5 100644 --- a/spring-web/src/main/java/org/springframework/web/client/RestClient.java +++ b/spring-web/src/main/java/org/springframework/web/client/RestClient.java @@ -548,7 +548,38 @@ public interface RestClient { * @param the type the response will be transformed to * @return the value returned from the exchange function */ - T exchange(ExchangeFunction exchangeFunction); + default T exchange(ExchangeFunction exchangeFunction) { + return exchange(exchangeFunction, true); + } + + /** + * Exchange the {@link ClientHttpResponse} for a type {@code T}. This + * can be useful for advanced scenarios, for example to decode the + * response differently depending on the response status: + *

+		 * Person person = client.get()
+		 *     .uri("/people/1")
+		 *     .accept(MediaType.APPLICATION_JSON)
+		 *     .exchange((request, response) -> {
+		 *         if (response.getStatusCode().equals(HttpStatus.OK)) {
+		 *             return deserialize(response.getBody());
+		 *         }
+		 *         else {
+		 *             throw new BusinessException();
+		 *         }
+		 *     });
+		 * 
+ *

Note: If {@code close} is {@code true}, + * then the response is {@linkplain ClientHttpResponse#close() closed} + * after the exchange function has been invoked. When set to + * {@code false}, the caller is responsible for closing the response. + * @param exchangeFunction the function to handle the response with + * @param close {@code true} to close the response after + * {@code exchangeFunction} is invoked, {@code false} to keep it open + * @param the type the response will be transformed to + * @return the value returned from the exchange function + */ + T exchange(ExchangeFunction exchangeFunction, boolean close); /**