java
38 lines · 6 steps
Streaming a file download with Java's HttpClient
A small class fetches a URL and streams the response body straight to disk without buffering it all in memory.
Explained by
highlit
1import java.io.IOException;
2import java.io.InputStream;
3import java.net.URI;
4import java.net.http.HttpClient;
5import java.net.http.HttpRequest;
6import java.net.http.HttpResponse;
7import java.nio.file.Files;
8import java.nio.file.Path;
9import java.nio.file.StandardCopyOption;
10
11public class RemoteFileDownloader {
12
13 private final HttpClient httpClient;
14
15 public RemoteFileDownloader(HttpClient httpClient) {
16 this.httpClient = httpClient;
17 }
18
19 public long download(URI source, Path destination) throws IOException, InterruptedException {
20 HttpRequest request = HttpRequest.newBuilder(source)
21 .header("Accept", "application/octet-stream")
22 .GET()
23 .build();
24
25 HttpResponse<InputStream> response =
26 httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());
27
28 if (response.statusCode() != 200) {
29 throw new IOException("Unexpected status " + response.statusCode() + " for " + source);
30 }
31
32 Files.createDirectories(destination.getParent());
33
34 try (InputStream body = response.body()) {
35 return Files.copy(body, destination, StandardCopyOption.REPLACE_EXISTING);
36 }
37 }
38}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Streaming the response body to disk keeps memory use flat regardless of file size.
- 2Injecting the HttpClient makes the downloader configurable and testable rather than hardcoding transport details.
- 3A try-with-resources block guarantees the network stream closes even when the copy fails.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/streaming-a-file-download-with-java-s-httpclient-explained-java-e53f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.