Sub topic 16
Streaming large responses and uploading or downloading files
This chapter assumes you can build an HttpClient and an HttpRequest, call send, and read a HttpResponse. It also assumes you know the BodyHandlers and BodyPublishers factories from earlier chapters. Here you will see how to move large bodies without holding them in memory.
Why `ofString` stops working for large bodies
BodyHandlers.ofString() reads the entire response into one String. ofByteArray() does the same with a byte[]. For a 2 GB download, both need at least that much heap, and ofString also decodes the bytes into characters. The usual failure is an OutOfMemoryError, often after a long wait.
A streaming handler passes data to its destination as it arrives, so memory use stays roughly constant regardless of body size.
| Handler | Result type | Memory use | Typical use |
|---|---|---|---|
| `ofString()` | `String` | Whole body | Small JSON or text |
| `ofByteArray()` | `byte[]` | Whole body | Small binary data |
| `ofFile(Path)` | `Path` | Small buffer | Downloads |
| `ofInputStream()` | `InputStream` | Small buffer | Custom processing of bytes |
| `ofLines()` | `Stream<String>` | Small buffer | Line-based text |
| `discarding()` | `Void` | None | Ignore the body |
Downloading to a file
BodyHandlers.ofFile(Path) writes the body to the given path. The response body is the Path itself, not the contents.
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 DownloadFile {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/big.bin"))
.GET()
.build();
HttpResponse<Path> response = client.send(
request, HttpResponse.BodyHandlers.ofFile(Path.of("download.bin")));
System.out.println(response.statusCode());
System.out.println("Saved to " + response.body());
}
}Several details matter in practice:
ofFilecreates the file and truncates it if it exists. To change this, pass open options:ofFile(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND).- The handler writes the body whatever the status code is. A 404 error page is saved into
download.binjust like a real file. CheckstatusCode()afterwards, and delete the file if the status is not 2xx. - The request
timeoutcovers the time until the response headers arrive, not the whole transfer. A slow download can run far longer than the timeout you set. ofFileDownload(Path, OpenOption...)(Java 11 and later) honors theContent-Dispositionheader's filename within a given directory. Use it only when you trust the server, since the server influences the file name.
If a transfer fails halfway, a partial file stays on disk. A safer pattern downloads to a temporary file and moves it into place only on success:
import java.io.IOException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class SafeDownload {
static void download(HttpClient client, HttpRequest request, Path target)
throws IOException, InterruptedException {
Path temp = Files.createTempFile(target.toAbsolutePath().getParent(), "dl-", ".part");
try {
HttpResponse<Path> response = client.send(
request, HttpResponse.BodyHandlers.ofFile(temp));
int status = response.statusCode();
if (status < 200 || status >= 300) {
throw new IOException("Download failed with status " + status);
}
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(temp);
}
}
}After a successful move, temp no longer exists, so deleteIfExists in the finally block does nothing. On any failure it removes the partial file.
Streaming with `ofInputStream`
ofInputStream() returns as soon as the headers arrive. The body is an InputStream that you read yourself. This suits cases where you transform bytes, such as decompressing or computing a checksum.
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.MessageDigest;
import java.util.HexFormat;
public class StreamChecksum {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/big.bin")).build();
HttpResponse<InputStream> response =
client.send(request, HttpResponse.BodyHandlers.ofInputStream());
MessageDigest digest = MessageDigest.getInstance("SHA-256");
long total = 0;
try (InputStream in = response.body()) {
byte[] buffer = new byte[8192];
int n;
while ((n = in.read(buffer)) != -1) {
digest.update(buffer, 0, n);
total += n;
}
}
System.out.println(total + " bytes, sha256=" + HexFormat.of().formatHex(digest.digest()));
}
}This example uses HexFormat, which needs Java 17 or later.
Always close the stream, preferably with try-with-resources. If you stop reading early and never close it, the connection cannot be reused and its resources stay held. Closing before the end of the body cancels the rest of the transfer.
Reading text line by line
ofLines() gives a Stream<String> that decodes the body lazily. It works well for large logs, CSV files and newline-delimited JSON.
HttpResponse<Stream<String>> response =
client.send(request, HttpResponse.BodyHandlers.ofLines());
try (Stream<String> lines = response.body()) {
long errors = lines.filter(line -> line.contains("ERROR")).count();
System.out.println(errors + " error lines");
}This needs import java.util.stream.Stream;. The stream holds a connection until it is consumed or closed, so close it with try-with-resources. Do not return it from a method that lets the caller forget to close it.
The streams are read on the calling thread, so a slow consumer applies backpressure to the connection. The client stops requesting more data until your code reads it.
Uploading files
BodyPublishers.ofFile(Path) streams a file as the request body. It reads the file in chunks, so a large upload does not need to fit in memory. It also sets the content length from the file size.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
public class UploadFile {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/upload"))
.header("Content-Type", "application/octet-stream")
.PUT(HttpRequest.BodyPublishers.ofFile(Path.of("backup.tar.gz")))
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
}
}ofFile throws FileNotFoundException when the request is built or sent if the file is missing. Handle that along with IOException.
Two other publishers help with streamed uploads:
BodyPublishers.ofInputStream(Supplier<InputStream>)takes a supplier because the client may need to read the body again, for example after a redirect or an authentication challenge. The supplier must return a fresh stream each time. Its length is unknown, so the client sends the body with chunked transfer encoding. Some servers reject chunked uploads.BodyPublishers.fromPublisher(publisher, contentLength)lets you give the length yourself, which avoids chunked encoding when you know the size.
Multipart form uploads
The client has no built-in multipart support. You have to build the body in the multipart/form-data format yourself. For modest files, you can concatenate byte arrays. Note the boundary in the Content-Type header.
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;
public class MultipartUpload {
public static void main(String[] args) throws Exception {
Path file = Path.of("report.pdf");
String boundary = "----" + UUID.randomUUID();
ByteArrayOutputStream out = new ByteArrayOutputStream();
String head = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getFileName() + "\"\r\n"
+ "Content-Type: application/pdf\r\n\r\n";
out.write(head.getBytes(StandardCharsets.UTF_8));
out.write(Files.readAllBytes(file));
out.write(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/files"))
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
.POST(HttpRequest.BodyPublishers.ofByteArray(out.toByteArray()))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
}
}This version loads the whole file into memory, so it suits small and medium files only. For large files, combine parts with BodyPublishers.concat (Java 16 and later), which joins several publishers into one body. Use ofByteArray for the head and tail and ofFile for the file between them.
HttpRequest.BodyPublisher body = HttpRequest.BodyPublishers.concat(
HttpRequest.BodyPublishers.ofByteArray(head.getBytes(StandardCharsets.UTF_8)),
HttpRequest.BodyPublishers.ofFile(file),
HttpRequest.BodyPublishers.ofByteArray(
("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)));Asynchronous streaming
Streaming handlers also work with sendAsync. The future completes when the headers arrive for ofInputStream and ofLines, and when the file is fully written for ofFile.
client.sendAsync(request, HttpResponse.BodyHandlers.ofFile(Path.of("download.bin")))
.thenApply(HttpResponse::body)
.thenAccept(path -> System.out.println("Saved to " + path))
.exceptionally(ex -> {
System.err.println("Download failed: " + ex);
return null;
})
.join();Do not do blocking reads from an InputStream inside the client's own executor threads in a callback you pass to thenApply. Reading a stream there can block the threads the client needs to deliver the data. Move such reads onto your own executor with thenApplyAsync(fn, myExecutor).
Data flow
Common mistakes
- Using
ofStringfor large or unknown-size responses. - Not checking the status code before trusting a file written by
ofFile. - Forgetting to close an
InputStreamorStreambody, which leaks the connection. - Expecting the request timeout to limit a whole download.
- Passing a supplier that returns the same
InputStreaminstance toofInputStream.
Exercise
You download a 5 GB archive with BodyHandlers.ofFile. The request has .timeout(Duration.ofSeconds(30)), and the transfer takes ten minutes. Does the request fail with HttpTimeoutException? What should you check after send returns?
Show answer
No. The request timeout applies until the response headers arrive, not to the whole body transfer, so a ten-minute download is not cut off by it. After send returns, check statusCode(). If it is not 2xx, the file contains an error response, so delete it or ignore it. A temporary file moved into place only on success avoids leaving a bad or partial file.
Exercise
Why does BodyPublishers.ofInputStream take a Supplier<InputStream> and not an InputStream, and what happens to the request framing when you use it?
Show answer
The client may need to send the body more than once, for example after a redirect or an authentication retry, so it needs a fresh stream each time, which the supplier provides. The length is unknown, so the request uses chunked transfer encoding unless you wrap the stream with fromPublisher and give the content length.