Video in progress
When downloading a large file with `java.net.http.HttpClient`, how do you write the response to disk rather than memory, and how do you resume an interrupted download?
BodyHandlers.ofFile(path) or ofInputStream() streams the response to disk; ofString/ofByteArray collect everything on the heap. To resume, you send Range: bytes=N-, check that 206 Partial Content came back, and write to the file with APPEND.
📖 Answer
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
Path part = target.resolveSibling(target.getFileName() + ".part");
long have = Files.exists(part) ? Files.size(part) : 0;
HttpRequest req = HttpRequest.newBuilder(uri)
.header("Range", "bytes=" + have + "-")
.header("If-Range", savedEtag) // if the file changed, the server sends it in full
.build();
How to open the file depends on the response code, so here I use ofInputStream() and write it myself:
HttpResponse<InputStream> resp = client.send(req, HttpResponse.BodyHandlers.ofInputStream());
var opts = resp.statusCode() == 206
? new OpenOption[]{StandardOpenOption.CREATE, StandardOpenOption.APPEND}
: new OpenOption[]{StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE};
try (InputStream in = resp.body(); OutputStream out = Files.newOutputStream(part, opts)) {
in.transferTo(out);
}
Important checks:
- if 200 comes back, the server ignored
Rangeor the file changed. In that case you write.partfrom the start, otherwise pieces of two different files get glued together; If-Range+ETag: so that if the file on the server was updated between the downloads, you don't append the new content to an old chunk;- Timeout.
HttpRequest.timeout()applies to waiting for the response headers; if streaming the body takes a long time, it doesn't help. For the body you watch the read speed yourself, or usesendAsync+orTimeoutwith an overall deadline; - Finish. Once fully downloaded, the checksum is verified and
.partis moved to the real name with an atomicmove, so no other code sees a half-finished file.
There is also a BodyHandlers.ofFile(path, CREATE, APPEND) overload, but it starts writing before the status code is checked, so for resuming I consider ofInputStream safer.
Sign up to mark studied questions and save your progress.