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 4300a354a0..f054ba055d 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 @@ -537,6 +537,13 @@ final class DefaultRestClient implements RestClient { return exchangeInternal(exchangeFunction, close); } + @Override + public T exchangeForRequiredValue(RequiredValueExchangeFunction exchangeFunction, boolean close) { + T value = exchangeInternal(exchangeFunction, close); + Assert.state(value != null, "The exchanged value must not be null"); + return value; + } + private @Nullable T exchangeInternal(ExchangeFunction exchangeFunction, boolean close) { Assert.notNull(exchangeFunction, "ExchangeFunction must not be null"); 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 79d4ef5839..c330136d8f 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 @@ -679,8 +679,8 @@ public interface RestClient { ResponseSpec retrieve(); /** - * Exchange the {@link ClientHttpResponse} for a type {@code T}. This - * can be useful for advanced scenarios, for example to decode the + * Exchange the {@link ClientHttpResponse} for a value of 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()
@@ -700,15 +700,44 @@ public interface RestClient {
 		 * function has been invoked.
 		 * @param exchangeFunction the function to handle the response with
 		 * @param  the type the response will be transformed to
-		 * @return the value returned from the exchange function
+		 * @return the value returned from the exchange function, potentially {@code null}
+		 * @see RequestHeadersSpec#exchangeForRequiredValue(RequiredValueExchangeFunction)
 		 */
 		default  @Nullable 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
+		 * Exchange the {@link ClientHttpResponse} for a value of 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: The response is + * {@linkplain ClientHttpResponse#close() closed} after the exchange + * function has been invoked. + * @param exchangeFunction the function to handle the response with + * @param the type the response will be transformed to + * @return the value returned from the exchange function, never {@code null} + */ + default T exchangeForRequiredValue(RequiredValueExchangeFunction exchangeFunction) { + return exchangeForRequiredValue(exchangeFunction, true); + } + + /** + * Exchange the {@link ClientHttpResponse} for a value of 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()
@@ -731,10 +760,40 @@ public interface RestClient {
 		 * @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
+		 * @return the value returned from the exchange function, potentially {@code null}
+		 * @see RequestHeadersSpec#exchangeForRequiredValue(RequiredValueExchangeFunction, boolean)
 		 */
 		 @Nullable T exchange(ExchangeFunction exchangeFunction, boolean close);
 
+		/**
+		 * Exchange the {@link ClientHttpResponse} for a value of 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, never {@code null} + */ + T exchangeForRequiredValue(RequiredValueExchangeFunction exchangeFunction, boolean close); + /** * Defines the contract for {@link #exchange(ExchangeFunction)}. @@ -744,15 +803,31 @@ public interface RestClient { interface ExchangeFunction { /** - * Exchange the given response into a type {@code T}. + * Exchange the given response into a value of type {@code T}. * @param clientRequest the request * @param clientResponse the response - * @return the exchanged type + * @return the exchanged value, potentially {@code null} * @throws IOException in case of I/O errors */ @Nullable T exchange(HttpRequest clientRequest, ConvertibleClientHttpResponse clientResponse) throws IOException; } + /** + * Variant of {@link ExchangeFunction} returning a non-null required value. + * @param the type the response will be transformed to + */ + @FunctionalInterface + interface RequiredValueExchangeFunction extends ExchangeFunction { + + /** + * Exchange the given response into a value of type {@code T}. + * @param clientRequest the request + * @param clientResponse the response + * @return the exchanged value, never {@code null} + * @throws IOException in case of I/O errors + */ + T exchange(HttpRequest clientRequest, ConvertibleClientHttpResponse clientResponse) throws IOException; + } /** * Extension of {@link ClientHttpResponse} that can convert the body. diff --git a/spring-web/src/main/kotlin/org/springframework/web/client/RestClientExtensions.kt b/spring-web/src/main/kotlin/org/springframework/web/client/RestClientExtensions.kt index 5159993951..12092af8df 100644 --- a/spring-web/src/main/kotlin/org/springframework/web/client/RestClientExtensions.kt +++ b/spring-web/src/main/kotlin/org/springframework/web/client/RestClientExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2002-2025 the original author or authors. + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,6 @@ package org.springframework.web.client import org.springframework.core.ParameterizedTypeReference import org.springframework.http.ResponseEntity -import org.springframework.web.client.RestClient.RequestHeadersSpec -import org.springframework.web.client.RestClient.RequestHeadersSpec.ExchangeFunction /** * Extension for [RestClient.RequestBodySpec.body] providing a `bodyWithType(...)` variant @@ -53,15 +51,6 @@ inline fun RestClient.ResponseSpec.body(): T? = inline fun RestClient.ResponseSpec.requiredBody(): T = body(object : ParameterizedTypeReference() {}) ?: throw NoSuchElementException("Response body is required") -/** - * Extension for [RestClient.RequestHeadersSpec.exchange] providing a `requiredExchange(...)` variant with a - * non-nullable return value. - * @throws NoSuchElementException if there is no response value - * @since 6.2.6 - */ -fun RequestHeadersSpec<*>.requiredExchange(exchangeFunction: ExchangeFunction, close: Boolean = true): T = - exchange(exchangeFunction, close) ?: throw NoSuchElementException("Response value is required") - /** * Extension for [RestClient.ResponseSpec.toEntity] providing a `toEntity()` variant * leveraging Kotlin reified type parameters. This extension is not subject to type @@ -71,5 +60,4 @@ fun RequestHeadersSpec<*>.requiredExchange(exchangeFunction: ExchangeFu * @since 6.1 */ inline fun RestClient.ResponseSpec.toEntity(): ResponseEntity = - toEntity(object : ParameterizedTypeReference() {}) - + toEntity(object : ParameterizedTypeReference() {}) \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/web/client/RestClientIntegrationTests.java b/spring-web/src/test/java/org/springframework/web/client/RestClientIntegrationTests.java index 36ec54c60c..c675334f92 100644 --- a/spring-web/src/test/java/org/springframework/web/client/RestClientIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/RestClientIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2002-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,6 +59,7 @@ import org.springframework.web.testfixture.xml.Pojo; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.params.provider.Arguments.argumentSet; @@ -765,6 +766,39 @@ class RestClientIntegrationTests { expectRequest(request -> assertThat(request.getPath()).isEqualTo("/greeting")); } + @ParameterizedRestClientTest + void exchangeForRequiredValue(ClientHttpRequestFactory requestFactory) { + startServer(requestFactory); + + prepareResponse(response -> response.setBody("Hello Spring!")); + + String result = this.restClient.get() + .uri("/greeting") + .header("X-Test-Header", "testvalue") + .exchangeForRequiredValue((request, response) -> new String(RestClientUtils.getBody(response), UTF_8)); + + assertThat(result).isEqualTo("Hello Spring!"); + + expectRequestCount(1); + expectRequest(request -> { + assertThat(request.getHeader("X-Test-Header")).isEqualTo("testvalue"); + assertThat(request.getPath()).isEqualTo("/greeting"); + }); + } + + @ParameterizedRestClientTest + @SuppressWarnings("DataFlowIssue") + void exchangeForNullRequiredValue(ClientHttpRequestFactory requestFactory) { + startServer(requestFactory); + + prepareResponse(response -> response.setBody("Hello Spring!")); + + assertThatIllegalStateException().isThrownBy(() -> this.restClient.get() + .uri("/greeting") + .header("X-Test-Header", "testvalue") + .exchangeForRequiredValue((request, response) -> null)); + } + @ParameterizedRestClientTest void requestInitializer(ClientHttpRequestFactory requestFactory) { startServer(requestFactory); diff --git a/spring-web/src/test/kotlin/org/springframework/web/client/RestClientExtensionsTests.kt b/spring-web/src/test/kotlin/org/springframework/web/client/RestClientExtensionsTests.kt index 703398e2c4..6e91590166 100644 --- a/spring-web/src/test/kotlin/org/springframework/web/client/RestClientExtensionsTests.kt +++ b/spring-web/src/test/kotlin/org/springframework/web/client/RestClientExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2002-2025 the original author or authors. + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,9 @@ package org.springframework.web.client import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.springframework.core.ParameterizedTypeReference -import org.springframework.http.HttpRequest -import org.springframework.web.client.RestClient.RequestHeadersSpec /** * Mock object based tests for [RestClient] Kotlin extensions @@ -62,24 +59,6 @@ class RestClientExtensionsTests { assertThrows { responseSpec.requiredBody() } } - @Test - fun `RequestHeadersSpec#requiredExchange`() { - val foo = Foo() - every { requestBodySpec.exchange(any>(), any()) } returns foo - val exchangeFunction: (HttpRequest, RequestHeadersSpec.ConvertibleClientHttpResponse) -> Foo? = - { _, _ -> foo } - val value = requestBodySpec.requiredExchange(exchangeFunction) - assertThat(value).isEqualTo(foo) - } - - @Test - fun `RequestHeadersSpec#requiredExchange with null response throws NoSuchElementException`() { - every { requestBodySpec.exchange(any>(), any()) } returns null - val exchangeFunction: (HttpRequest, RequestHeadersSpec.ConvertibleClientHttpResponse) -> Foo? = - { _, _ -> null } - assertThrows { requestBodySpec.requiredExchange(exchangeFunction) } - } - @Test fun `ResponseSpec#toEntity with reified type parameters`() { responseSpec.toEntity>()