Sub topic 5
Choosing a BodyHandler for the response
This chapter assumes you can build an HttpClient and an HttpRequest, and that you have called client.send(...) at least once. It also assumes you know the basic HTTP status codes and Java generics. Here you will learn what a BodyHandler does, how the built-in handlers differ, and how to pick one for a given response.
What a BodyHandler is
Every call to send or sendAsync takes a second argument that says how to turn the bytes of the response body into a Java object. That argument is a BodyHandler<T>. The type parameter T becomes the type of response.body().
A BodyHandler is a functional interface. It runs after the status line and headers arrive, but before any body bytes are read. It receives a ResponseInfo (status code, headers, HTTP version) and returns a BodySubscriber<T>. The subscriber then consumes the body bytes as they arrive.
This ordering has a practical consequence. A handler can look at the status code or Content-Type and choose a different way of reading the body.
The built-in handlers
The HttpResponse.BodyHandlers class provides the common cases.
| Handler | `body()` type | Use it when |
|---|---|---|
| `ofString()` | `String` | The body is small text such as JSON or HTML |
| `ofString(Charset)` | `String` | You must force a charset |
| `ofByteArray()` | `byte[]` | The body is small binary data |
| `ofFile(Path)` | `Path` | You want the body saved to a file |
| `ofFileDownload(Path, OpenOption...)` | `Path` | You want the server's suggested file name inside a directory |
| `ofInputStream()` | `InputStream` | You want to read incrementally on your own thread |
| `ofLines()` | `Stream<String>` | The body is line-oriented text |
| `ofByteArrayConsumer(Consumer)` | `Void` | You want to process chunks as they arrive |
| `discarding()` | `Void` | You only care about status and headers |
| `replacing(T)` | `T` | You discard the body and return a fixed value |
Only ofString, ofByteArray, discarding and replacing complete with a body that is fully available when send returns. The streaming handlers behave differently, as covered below.
Text: ofString and charsets
ofString() decodes the body with the charset named in the response's Content-Type header. If the header is missing, or names an unsupported charset, it falls back to UTF-8. ofString(Charset) ignores the header and always uses the charset you pass.
import java.nio.charset.StandardCharsets;
import java.net.http.HttpResponse.BodyHandlers;
HttpResponse<String> legacy = client.send(
request, BodyHandlers.ofString(StandardCharsets.ISO_8859_1));Use the explicit form only when you know the server mislabels its responses.
Both ofString and ofByteArray hold the whole body in memory. For a multi-gigabyte download, that is the wrong choice.
Binary data and files
Use ofByteArray() for small binary payloads such as thumbnails.
For anything large, write to disk with ofFile. The body() of the response is the Path you supplied.
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.net.http.HttpResponse.BodyHandlers;
Path target = Path.of("report.pdf");
HttpResponse<Path> response = client.send(request,
BodyHandlers.ofFile(target,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING));
System.out.println(response.statusCode() + " -> " + response.body());The one-argument ofFile(Path) opens the file with CREATE and WRITE only. If report.pdf already exists and is longer than the new download, the extra old bytes stay at the end of the file. Pass TRUNCATE_EXISTING as above to avoid that.
ofFile writes the body whatever the status code is. A 404 error page will be saved into your file. Either check the status afterward and delete the file, or choose the handler by status, as shown later in this chapter.
Streaming: ofInputStream, ofLines and consumers
Streaming handlers return as soon as the headers arrive. The body is read while your code consumes it. Because they hold network resources, you must close what they return.
HttpResponse<Stream<String>> response =
client.send(request, BodyHandlers.ofLines());
try (Stream<String> lines = response.body()) {
lines.limit(5).forEach(System.out::println);
}Closing the stream early, as limit(5) followed by the try block does here, cancels the rest of the transfer. If you forget to close an InputStream or Stream, the connection may stay tied up and later requests can suffer.
ofInputStream() works the same way and suits parsers that read from an InputStream, including many JSON libraries.
ofByteArrayConsumer takes a Consumer<Optional<byte[]>>. The client calls it with each chunk and with an empty Optional at the end. The response body is Void, so all the work happens in your consumer.
Ignoring the body
If you only need the status or a header, such as a HEAD request or a DELETE that returns nothing useful, use discarding(). The client reads and throws away the body so the connection can be reused. response.body() returns null.
Use replacing(value) when you want a typed placeholder instead of null.
Choosing a handler by status code
Because the handler sees ResponseInfo first, you can pick a subscriber per response. This handler keeps the body only for a 200 and discards everything else:
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodySubscribers;
import java.nio.charset.StandardCharsets;
BodyHandler<String> onlyOk = info -> info.statusCode() == 200
? BodySubscribers.ofString(StandardCharsets.UTF_8)
: BodySubscribers.replacing("");The same idea protects ofFile. Return BodySubscribers.ofFile(path) for success and BodySubscribers.replacing(path) for errors, so no file is written when the request fails.
Writing your own with mapping
BodySubscribers.mapping wraps an existing subscriber and converts its result. This builds a custom handler without implementing the subscriber interface yourself.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodySubscribers;
import java.nio.charset.StandardCharsets;
public class LengthOfBody {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest
.newBuilder(URI.create("https://example.com/")).build();
BodyHandler<Integer> lengthHandler = info ->
BodySubscribers.mapping(
BodySubscribers.ofString(StandardCharsets.UTF_8),
String::length);
HttpResponse<Integer> response = client.send(request, lengthHandler);
System.out.println("Characters: " + response.body());
}
}A common use is to map the string straight to a domain object with a JSON library, so response.body() is already your type. The mapping function runs on a client thread, so keep it quick.
Common mistakes
- Using
ofStringfor a large download and running out of memory. UseofFileorofInputStream. - Not closing the
StreamfromofLinesor theInputStreamfromofInputStream. - Assuming
ofFilefails on a 4xx or 5xx response. It writes the error body to your file. - Calling
response.body()afterdiscarding()and expecting content. It isnull. - Forcing a charset with
ofString(Charset)and breaking a response that was correctly labeled.
Decision guide
Exercise
You download a 2 GB archive with ofFile(Path.of("data.zip")), and the server answers 404 with a short HTML error page. What ends up in data.zip, and how would you change the handler so no file is written on errors?
Show answer
The HTML error page is written to data.zip, because ofFile writes the body regardless of status. Use a custom BodyHandler that checks info.statusCode(): return BodySubscribers.ofFile(path) when the status is 200, and BodySubscribers.replacing(path) otherwise, so nothing is written for errors. Also pass TRUNCATE_EXISTING if an older, longer data.zip might already exist.