Skip to content

Commit cb0c5f5

Browse files
committed
Allow RestClient::exchange to keep connection open
This commit introduces an overloaded version of RestClient::exchange, adding a boolean parameter that indicates whether the connection is closed after the exchange function is executed. See gh-29552
1 parent 8691173 commit cb0c5f5

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -360,8 +360,8 @@ public ResponseSpec retrieve() {
360360
}
361361

362362
@Override
363-
public <T> T exchange(ExchangeFunction<T> exchangeFunction) {
364-
return exchangeInternal(exchangeFunction, true);
363+
public <T> T exchange(ExchangeFunction<T> exchangeFunction, boolean close) {
364+
return exchangeInternal(exchangeFunction, close);
365365
}
366366

367367
private <T> T exchangeInternal(ExchangeFunction<T> exchangeFunction, boolean close) {

spring-web/src/main/java/org/springframework/web/client/RestClient.java

+32-1
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,38 @@ interface RequestHeadersSpec<S extends RequestHeadersSpec<S>> {
548548
* @param <T> the type the response will be transformed to
549549
* @return the value returned from the exchange function
550550
*/
551-
<T> T exchange(ExchangeFunction<T> exchangeFunction);
551+
default <T> T exchange(ExchangeFunction<T> exchangeFunction) {
552+
return exchange(exchangeFunction, true);
553+
}
554+
555+
/**
556+
* Exchange the {@link ClientHttpResponse} for a type {@code T}. This
557+
* can be useful for advanced scenarios, for example to decode the
558+
* response differently depending on the response status:
559+
* <p><pre>
560+
* Person person = client.get()
561+
* .uri("/people/1")
562+
* .accept(MediaType.APPLICATION_JSON)
563+
* .exchange((request, response) -&gt; {
564+
* if (response.getStatusCode().equals(HttpStatus.OK)) {
565+
* return deserialize(response.getBody());
566+
* }
567+
* else {
568+
* throw new BusinessException();
569+
* }
570+
* });
571+
* </pre>
572+
* <p><strong>Note:</strong> If {@code close} is {@code true},
573+
* then the response is {@linkplain ClientHttpResponse#close() closed}
574+
* after the exchange function has been invoked. When set to
575+
* {@code false}, the caller is responsible for closing the response.
576+
* @param exchangeFunction the function to handle the response with
577+
* @param close {@code true} to close the response after
578+
* {@code exchangeFunction} is invoked, {@code false} to keep it open
579+
* @param <T> the type the response will be transformed to
580+
* @return the value returned from the exchange function
581+
*/
582+
<T> T exchange(ExchangeFunction<T> exchangeFunction, boolean close);
552583

553584

554585
/**

0 commit comments

Comments
 (0)