Sub topic 4
Choosing a BodyHandler for the response
This chapter assumes Java 11 or later, basic HTTP knowledge, and familiarity with checked exceptions. You already know that an HTTP response has a status code, headers, and a body. A BodyHandler tells HttpClient how to convert that body into a Java value.
The handler is supplied to send or sendAsync:
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());The type parameter of HttpResponse matches the selected handler. Here, ofString() produces HttpResponse<String>.
Select a handler by response size and use
| Handler | Body type | Typical use |
|---|---|---|
| `ofString()` | `String` | Small text or JSON responses |
| `ofByteArray()` | `byte[]` | Small binary data |
| `ofFile(path)` | `Path` | Large downloads |
| `ofLines()` | `Stream<String>` | Text processed line by line |
| `discarding()` | `Void` | Requests where the body is irrelevant |
ofString() is convenient, but it stores the complete response in memory. Avoid it for untrusted or very large responses. ofFile() writes the response directly to a file, which limits memory use.
Example: text, lines, and files
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.util.stream.Stream;
public class ResponseBodies {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://example.com/"))
.GET()
.build();
HttpResponse<String> text = client.send(
request, HttpResponse.BodyHandlers.ofString());
System.out.println("Characters: " + text.body().length());
HttpResponse<Path> file = client.send(
request,
HttpResponse.BodyHandlers.ofFile(Path.of("example.html")));
System.out.println("Saved to: " + file.body());
HttpResponse<Stream<String>> lines = client.send(
request, HttpResponse.BodyHandlers.ofLines());
try (Stream<String> stream = lines.body()) {
stream.limit(3).forEach(System.out::println);
}
}
}The ofLines() body is a stream. Close it after processing, especially when reading a long response. A stream is lazy, so lines are consumed as the program requests them rather than all being stored at once.
Custom response processing
The built-in handlers cover common cases. For special formats, use BodyHandlers.mapping(...) with a custom BodySubscriber, or read a string and pass it to a separate parser. HttpClient does not parse JSON by itself. A library such as Jackson can convert the string into an object.
A body handler does not decide whether the request succeeded. A 404 response can still produce a normal HttpResponse<String>. Check the status code separately before interpreting the body.
Exercise
Which handler is the safer default for downloading a multi-gigabyte file?
Show answer
BodyHandlers.ofFile(path), because it writes the response to disk instead of keeping the complete body in memory.