Sub topic 12
Low-level access with exchange()
The retrieve() method covers most calls. You describe the request, ask for the body, and let RestClient turn error statuses into exceptions. Sometimes that is too little control. You may need to branch on the status code without throwing, read a response header, stream a large body to disk, or build an error message from the request and response together. For these cases, RestClient offers exchange().
This chapter assumes you know the earlier chapters of this tutorial: building a RestClient, URI templates, body(), and onStatus. It also assumes Java 17 lambdas and checked exceptions.
What exchange() does
exchange() is the second way to finish a request, next to retrieve(). You pass it a function. RestClient sends the request and calls your function with two arguments. The function's return value becomes the return value of exchange().
The two arguments are:
- The
HttpRequestthat was sent. It gives you the method, URI, and request headers. - A
ConvertibleClientHttpResponse. This is aClientHttpResponsewith status, headers, and a rawInputStreambody. It also hasbodyTo(Class)andbodyTo(ParameterizedTypeReference), which use the same message converters asretrieve().body().
Here is the simplest possible use, equivalent to retrieve().body(Todo.class) but with the response in your hands:
import org.springframework.web.client.RestClient;
record Todo(long id, String title, boolean completed) {}
class TodoExchangeService {
private final RestClient restClient;
TodoExchangeService(RestClient todoRestClient) {
this.restClient = todoRestClient;
}
Todo findById(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.exchange((request, response) -> response.bodyTo(Todo.class));
}
}This looks like a longer way to do the same thing, and for a success path it is. The difference shows up when the server answers with an error.
How exchange() differs from retrieve()
retrieve() applies status handling for you. A 4xx or 5xx response triggers the default error handler or any onStatus handlers you registered. exchange() does none of that. Your function receives every response as is, and you decide what each status means.
| Aspect | `retrieve()` | `exchange()` |
|---|---|---|
| Error statuses (4xx, 5xx) | Throw `RestClientResponseException` subclasses by default | Never thrown for you. You inspect the status |
| `onStatus` handlers | Applied | Not available |
| Access to request and response headers | Only through `toEntity()` for the response | Direct, for both request and response |
| Access to the raw body stream | No | Yes, through `getBody()` |
| Response lifetime | Closed by `RestClient` after the terminal call | Closed after your function returns, by default |
| Typical use | Everyday calls | Branching on status, streaming, custom diagnostics |
The first row is the one that surprises people. Code that relies on exceptions for failure, such as a catch (RestClientResponseException e) block, does not see HTTP errors from exchange(). The call returns normally and your function runs with a 404 or 500 response.
Branching on the status code
A common use is turning "not found" into an absent value instead of an exception. With retrieve() you would register onStatus and throw, then catch somewhere else. With exchange() you handle it in one place:
import java.util.Optional;
import org.springframework.http.HttpStatusCode;
import org.springframework.web.client.RestClient;
class TodoApiException extends RuntimeException {
TodoApiException(String message) {
super(message);
}
}
class TodoLookup {
private final RestClient restClient;
TodoLookup(RestClient todoRestClient) {
this.restClient = todoRestClient;
}
Optional<Todo> findIfPresent(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.exchange((request, response) -> {
HttpStatusCode status = response.getStatusCode();
if (status.value() == 404) {
return Optional.empty();
}
if (status.isError()) {
throw new TodoApiException(
request.getMethod() + " " + request.getURI()
+ " failed with " + status.value());
}
return Optional.of(response.bodyTo(Todo.class));
});
}
}Three details matter here.
- The error check comes before
bodyTo. If you callbodyTo(Todo.class)on a 500 response, the converter tries to read the error payload as aTodo. That either fails with a confusing deserialization error or produces aTodowith default values. HttpStatusCode.isError()is true for both 4xx and 5xx. It lets you handle one specific status and still reject everything else.- The lambda can throw checked
IOExceptions, because the functional interface declares it. You do not need a try/catch aroundgetStatusCode()orbodyTo.
Reading headers together with the status
retrieve().toEntity() also gives you headers, but only after the default status handling has run. With exchange() you can read a header and the status in one place. A typical case is a POST that answers 201 Created with a Location header and no body:
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClient;
record NewTodo(String title) {}
class TodoCreator {
private final RestClient restClient;
TodoCreator(RestClient todoRestClient) {
this.restClient = todoRestClient;
}
URI createAndReturnLocation(NewTodo newTodo) {
return restClient.post()
.uri("/todos")
.contentType(MediaType.APPLICATION_JSON)
.body(newTodo)
.exchange((request, response) -> {
if (response.getStatusCode().value() != 201) {
throw new IllegalStateException(
"Expected 201 but got " + response.getStatusCode().value());
}
URI location = response.getHeaders().getLocation();
if (location == null) {
throw new IllegalStateException("201 response had no Location header");
}
return location;
});
}
}HttpHeaders.getLocation() returns null when the header is absent, so the example checks for it. A server that returns 200 or 204 instead of 201 is a contract violation worth reporting, and exchange() is where you can see that.
Streaming a response body
bodyTo reads the whole body into memory and converts it. For a large file that is wasteful. Inside the function, getBody() returns the raw InputStream, so you can copy it straight to disk:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.springframework.web.client.RestClient;
class ExportDownloader {
private final RestClient restClient;
ExportDownloader(RestClient todoRestClient) {
this.restClient = todoRestClient;
}
long download(Path target) {
return restClient.get()
.uri("/todos/export")
.exchange((request, response) -> {
if (response.getStatusCode().isError()) {
throw new IOException(
"Export failed with status " + response.getStatusCode().value());
}
return Files.copy(response.getBody(), target,
StandardCopyOption.REPLACE_EXISTING);
});
}
}Files.copy returns the number of bytes written, and that becomes the return value of exchange(). The stream is consumed entirely inside the function, which brings up the most important rule about this method.
The response is closed when your function returns
By default, RestClient closes the response as soon as your function returns. That releases the connection. It also invalidates the body stream. Anything you read from the response must be read inside the function.
There is an overload, exchange(function, close), where passing false leaves the response open after the function returns. This lets you hand a stream to a caller. It also makes you responsible for closing the response yourself. If you forget, the connection is never returned to the pool, and under load the client eventually stalls waiting for a free connection. Use close = false only when you can show that the caller will always close it, and prefer copying inside the function when you can.
Common errors
- Assuming exceptions for HTTP errors. A
catch (RestClientResponseException e)around anexchange()call does not fire for a 404 or 500. Check the status in the function. - Calling
bodyTobefore checking the status, which tries to map an error payload to your success type. - Reading the body outside the function, after the response has been closed.
- Calling
bodyTotwice. The body stream is consumed by the first read. If you need the content twice, read it once into aStringorbyte[]and keep that value. - Expecting a non-null result from
bodyTo. When the response has no body, for example on204, the result can benull. Handle that case if the status allows an empty body. - Using
exchange()for everything. If you only want a typed body and default error handling,retrieve()is shorter and harder to get wrong.
Testing exchange() code
MockRestServiceServer works the same way for exchange() as for retrieve(). The mock replaces the request factory, so your function receives a response built from withStatus(...), withSuccess(...), or withResourceNotFound(). That makes the status branches easy to test without a network. Write one test per branch: a 200 with a body, a 404, and a 500.
When to choose exchange()
Use retrieve() by default. Move to exchange() when at least one of these holds:
- Your logic depends on a specific status code, and you want a return value instead of an exception.
- You need both the status and a header, or the request URI and the response, in one place.
- You must stream the body instead of loading it into memory.
- You need to build a diagnostic message from the full request and response.
If you only need to translate one or two statuses into exceptions, onStatus on retrieve() is simpler and keeps the default handling for everything else.
Exercise
A teammate writes restClient.get().uri("/reports/{id}", id).exchange((req, res) -> res.getBody()) and then reads the returned InputStream in the calling method. The read fails. Why, and how would you fix it so the report is saved to a file?
Show answer
By default exchange() closes the response as soon as the function returns, so the InputStream is already invalid when the caller reads it. Fix it by consuming the stream inside the function, for example exchange((req, res) -> Files.copy(res.getBody(), target, StandardCopyOption.REPLACE_EXISTING)), after checking res.getStatusCode().isError() first. Passing false as the second argument would keep the response open, but then the caller must close it to avoid leaking the connection.
Exercise
You switch a method from retrieve().body(Todo.class) to exchange((req, res) -> res.bodyTo(Todo.class)) and a 500 response from the server no longer throws an exception. What happens instead, and what should you add?
Show answer
exchange() does not apply default status handling, so the 500 response reaches your function and bodyTo(Todo.class) tries to convert the error payload into a Todo. This either fails with a deserialization error or returns a meaningless object. Add a status check before bodyTo, such as if (res.getStatusCode().isError()) { throw ...; }, so the function fails with a clear error for 4xx and 5xx responses.