Sub topic 15
Streaming Large Responses and Uploading or Downloading Files
Assume you know Java 11+, HttpClient, HTTP methods, and checked exceptions. This chapter focuses on keeping file transfers out of memory.
Downloading directly to a file
BodyHandlers.ofString() stores the complete response as a String. That is convenient for small text responses, but it is a poor choice for a large archive or video. BodyHandlers.ofFile writes response bytes to a Path as the response arrives.
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.time.Duration;
public class FileTransfer {
public static void main(String[] args) throws Exception {
Path destination = Path.of("download.bin");
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://example.com/file.bin"))
.timeout(Duration.ofMinutes(2))
.GET()
.build();
HttpResponse<Path> response = client.send(
request,
HttpResponse.BodyHandlers.ofFile(destination));
if (response.statusCode() >= 200 && response.statusCode() < 300) {
System.out.println("Saved to " + response.body());
} else {
System.err.println("Download failed: " + response.statusCode());
}
}
}The response body has type Path, not String. Check the status before treating the file as a successful download. An error response might otherwise be written to the destination file.
Processing lines without building one large string
For a large text response, BodyHandlers.ofLines() returns a Stream<String>. Process each line and close the stream when finished.
HttpResponse<java.util.stream.Stream<String>> response = client.send(
request,
HttpResponse.BodyHandlers.ofLines());
try (java.util.stream.Stream<String> lines = response.body()) {
lines.filter(line -> line.contains("ERROR"))
.forEach(System.out::println);
}This approach reduces memory use, but it does not remove the need for timeouts and status checks.
Uploading a file
Use BodyPublishers.ofFile when the request body already exists as a file. The client reads the file while sending the request.
HttpRequest upload = HttpRequest.newBuilder(
URI.create("https://api.example.com/uploads"))
.header("Content-Type", "application/octet-stream")
.POST(HttpRequest.BodyPublishers.ofFile(Path.of("report.pdf")))
.build();
HttpResponse<String> result = client.send(
upload,
HttpResponse.BodyHandlers.ofString());
if (result.statusCode() >= 200 && result.statusCode() < 300) {
System.out.println(result.body());
}The server may require additional headers, such as an authorization token, a filename, or a checksum. Follow that API's upload contract.
Choosing the transfer strategy
Exercise
Which body handler should you choose to save a large binary response directly to disk?
Show answer
Use HttpResponse.BodyHandlers.ofFile with a destination Path.