Sub topic 12
Low-level access with exchange()
This chapter assumes you can build a RestClient, send a GET request, and read a body with retrieve().body(). It also assumes you know what onStatus does. The earlier chapters cover all of that.
Why exchange() exists
retrieve() covers most calls. It checks the status, applies your onStatus handlers, and converts the body. Sometimes you need more control:
- You want to branch on the status code and read the body differently for each one.
- You need response headers and the body together, such as a
Locationheader plus JSON. - You want to stream the body instead of loading it into an object.
- A 404 is a normal result for you, not an error.
exchange() gives you the raw request and response and lets you decide everything.
How the call works
You pass exchange() a function with two arguments, the request and the response. Whatever your function returns becomes the return value of exchange().
Two rules follow from this flow:
- No status handling is applied.
onStatushandlers and the defaultRestClientResponseExceptiondo not run. A 500 response reaches your function like any other. - The response is closed when your function returns. Read what you need inside the function. Do not return the raw stream.
Branching on status
This example returns null for a 404 and throws for other errors. It reads the error body for the message.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClient;
record Todo(long id, String title, boolean completed) {}
class TodoLookup {
private final RestClient restClient;
TodoLookup(RestClient todoRestClient) {
this.restClient = todoRestClient;
}
Todo findOrNull(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.accept(MediaType.APPLICATION_JSON)
.exchange((request, response) -> {
int status = response.getStatusCode().value();
if (status == 404) {
return null;
}
if (response.getStatusCode().isError()) {
String body = new String(
response.getBody().readAllBytes(), StandardCharsets.UTF_8);
throw new IllegalStateException(
request.getMethod() + " " + request.getURI()
+ " failed with " + status + ": " + body);
}
return response.bodyTo(Todo.class);
});
}
}The response object is a ConvertibleClientHttpResponse. It offers getStatusCode(), getHeaders(), and getBody() for the raw stream. It also offers bodyTo(Class) and bodyTo(ParameterizedTypeReference), which use the same message converters as retrieve().body().
The lambda may throw IOException, so you do not need try/catch around getBody().
Reading headers together with the body
A common case is a POST where the server answers 201 with a Location header and no useful body:
import java.net.URI;
import org.springframework.http.MediaType;
URI createAndGetLocation(NewTodo newTodo) {
return restClient.post()
.uri("/todos")
.contentType(MediaType.APPLICATION_JSON)
.body(newTodo)
.exchange((request, response) -> {
if (response.getStatusCode().isError()) {
throw new IllegalStateException("Create failed: " + response.getStatusCode());
}
return response.getHeaders().getLocation();
});
}
record NewTodo(String title) {}Streaming a large body
For a large download, copy the stream straight to disk instead of building an object:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
long download(String uri, Path target) {
return restClient.get()
.uri(uri)
.exchange((request, response) -> {
if (response.getStatusCode().isError()) {
throw new IllegalStateException("Download failed: " + response.getStatusCode());
}
return Files.copy(response.getBody(), target, StandardCopyOption.REPLACE_EXISTING);
});
}This returns the number of bytes copied. The copy finishes before the function returns, so closing the response afterward is safe.
Common errors
- Forgetting that errors are silent. With
exchange(), a 500 is not an exception. If you skip the status check,bodyTo()may fail with a confusing conversion error or return a wrong object. - Returning the stream. Returning
response.getBody()hands the caller a closed stream. Return a fully read value. - Using
exchange()whenretrieve()is enough. If you only need to map one or two statuses,onStatusis shorter and keeps the happy path readable.
When to choose it
| Need | Use |
|---|---|
| Map the body, throw on errors | `retrieve().body()` |
| Map one status to a domain exception | `retrieve().onStatus(...)` |
| Status, headers, and body in one decision | `exchange()` |
| Stream a large body | `exchange()` |
Exercise
A call to restClient.get().uri("/todos/9").exchange(...) hits a server that answers 503 with an HTML error page. Your function only contains return response.bodyTo(Todo.class);. Why is this a problem, and what should you add?
Show answer
exchange() skips the default error handling, so the 503 reaches your function and bodyTo(Todo.class) tries to convert HTML to a Todo. That fails with a conversion error, or the failure is hidden, and the real cause (the 503) is lost. Check response.getStatusCode().isError() first and throw an exception that includes the status and, if useful, the body text.