Java HttpClient Deep Dive
The basics of java.net.http.HttpClient fit in a few lines. Production use raises more questions: should the client be shared, how do authentication and cookies work, how to retry safely, and how to handle large responses. Each section below answers one with a program against a local test server.
Contents
How java.net.http.HttpClient works
HttpClientHttpURLConnectionHttpClientHttpRequestStringsendsendAsyncCompletableFuture
The client speaks HTTP/1.1 and HTTP/2. Over TLS it offers HTTP/2 during the handshake and falls back to HTTP/1.1 if the server declines; over plain HTTP, as with the local test server here, it uses HTTP/1.1 unless told otherwise. With HTTP/1.1 each connection carries one request at a time, so the pool opens several connections for concurrent requests; with HTTP/2 many requests share one connection.
| API | Since | Notes |
|---|---|---|
HttpURLConnection | Java 1.1 | Blocking, HTTP/1.1 only, awkward API; still found in old code |
HttpClient | Java 11 (JEP 321) | HTTP/2, async, WebSocket, immutable builders |
HttpClient.close() | Java 21 | The client is AutoCloseable |
| HTTP/3 | Java 26 (JEP 517) | Opt-in: set HttpClient.Version.HTTP_3 |
All programs run on JDK 21 against a local test server, so no network access is needed.
The test server
All examples run against this server, built on the JDK's HttpServer/secure/login/flaky/big
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
// Local server with endpoints that exercise HttpClient features
final class TestServer {
final HttpServer server;
final Set<Integer> clientPorts = ConcurrentHashMap.newKeySet();
final AtomicInteger flakyCalls = new AtomicInteger();
TestServer() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.createContext("/ping", ex -> {
clientPorts.add(ex.getRemoteAddress().getPort()); // one port per TCP connection
send(ex, 200, "pong");
});
server.createContext("/secure", ex -> {
String auth = ex.getRequestHeaders().getFirst("Authorization");
String expected = "Basic " + Base64.getEncoder().encodeToString(
"ana:s3cret".getBytes(StandardCharsets.UTF_8));
if (!expected.equals(auth)) {
ex.getResponseHeaders().add("WWW-Authenticate", "Basic realm=\"demo\"");
send(ex, 401, "login required");
} else {
send(ex, 200, "welcome ana");
}
});
server.createContext("/login", ex -> {
ex.getResponseHeaders().add("Set-Cookie", "session=abc123; Path=/; HttpOnly");
send(ex, 200, "logged in");
});
server.createContext("/me", ex -> {
String cookie = ex.getRequestHeaders().getFirst("Cookie");
send(ex, 200, "cookie received: " + cookie);
});
server.createContext("/flaky", ex -> {
if (flakyCalls.incrementAndGet() <= 2) {
send(ex, 503, "busy");
} else {
send(ex, 200, "finally ok");
}
});
server.createContext("/big", ex -> {
ex.sendResponseHeaders(200, 0); // 0 = chunked, unknown length
try (OutputStream out = ex.getResponseBody()) {
for (int i = 1; i <= 100000; i++) {
out.write(("line " + i + "\n").getBytes(StandardCharsets.UTF_8));
}
}
});
server.createContext("/slow", ex -> {
try {
Thread.sleep(300); // a slow backend
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
send(ex, 200, "slow answer");
});
server.createContext("/old", ex -> {
ex.getResponseHeaders().add("Location", "/ping");
send(ex, 301, "moved");
});
server.createContext("/echo", ex -> {
String type = ex.getRequestHeaders().getFirst("Content-Type");
String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
send(ex, 201, ex.getRequestMethod() + " " + type + " " + body);
});
server.start();
}
String url(String path) {
return "http://127.0.0.1:" + server.getAddress().getPort() + path;
}
static void send(HttpExchange ex, int status, String body) throws IOException {
byte[] b = body.getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(status, b.length);
try (OutputStream out = ex.getResponseBody()) {
out.write(b);
}
}
}
Share one client: connection reuse
An HttpClient
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ConnectionReuse {
public static void main(String[] args) throws Exception {
TestServer ts = new TestServer();
HttpRequest ping = HttpRequest.newBuilder(URI.create(ts.url("/ping"))).build();
// One shared client: requests reuse a kept-alive connection
try (HttpClient shared = HttpClient.newHttpClient()) {
for (int i = 0; i < 10; i++) {
shared.send(ping, HttpResponse.BodyHandlers.ofString());
}
}
System.out.println("10 requests, one shared client: " + ts.clientPorts.size()
+ " TCP connection(s)");
// A new client per request: a new connection (and handshake) every time
ts.clientPorts.clear();
for (int i = 0; i < 10; i++) {
try (HttpClient fresh = HttpClient.newHttpClient()) {
fresh.send(ping, HttpResponse.BodyHandlers.ofString());
}
}
System.out.println("10 requests, new client each time: " + ts.clientPorts.size()
+ " TCP connection(s)");
ts.server.stop(0);
}
}
Output:
10 requests, one shared client: 1 TCP connection(s)
10 requests, new client each time: 10 TCP connection(s)
The shared client used a single connection for all 10 requests; new clients opened 10. Over the internet each new connection costs a TCP handshake plus, for HTTPS, a TLS handshake, often more time than the request itself. Create one HttpClient
Authentication and cookies
Two client-level features handle state across requests:
- An
supplies credentials when a server answersAuthenticator with a401 challenge. The client then repeats the request with anWWW-Authenticate header.Authorization - A
, usuallyCookieHandler , stores cookies fromCookieManager headers and sends them back on matching requests.Set-Cookie
The program calls the protected endpoint and the login/profile pair with and without each feature.
import java.net.Authenticator;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class AuthAndCookies {
static String get(HttpClient c, String url) throws Exception {
HttpResponse<String> r = c.send(HttpRequest.newBuilder(URI.create(url)).build(),
HttpResponse.BodyHandlers.ofString());
return r.statusCode() + " " + r.body();
}
public static void main(String[] args) throws Exception {
TestServer ts = new TestServer();
try (HttpClient plain = HttpClient.newHttpClient()) {
System.out.println("no authenticator: " + get(plain, ts.url("/secure")));
}
// The Authenticator answers the server's 401 challenge and the client retries
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println(" authenticator asked for realm \"" + getRequestingPrompt()
+ "\"");
return new PasswordAuthentication("ana", "s3cret".toCharArray());
}
};
try (HttpClient withAuth = HttpClient.newBuilder().authenticator(auth).build()) {
System.out.println("with authenticator: " + get(withAuth, ts.url("/secure")));
}
// Without a cookie handler, cookies from responses are ignored
try (HttpClient noCookies = HttpClient.newHttpClient()) {
get(noCookies, ts.url("/login"));
System.out.println("no cookie handler: " + get(noCookies, ts.url("/me")));
}
CookieManager cookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
try (HttpClient withCookies = HttpClient.newBuilder().cookieHandler(cookies).build()) {
get(withCookies, ts.url("/login"));
System.out.println("with CookieManager: " + get(withCookies, ts.url("/me")));
}
ts.server.stop(0);
}
}
Output:
no authenticator: 401 login required
authenticator asked for realm "demo"
with authenticator: 200 welcome ana
no cookie handler: 200 cookie received: null
with CookieManager: 200 cookie received: session=abc123
- Without an authenticator, the 401 is simply returned. With one, the client asked for credentials for realm "demo" and retried transparently, so the caller only sees the 200.
- By default
keeps no cookies, so the session cookie fromHttpClient was lost. With a/login , it was stored and sent on the next request.CookieManager - For bearer tokens (OAuth, JWT), skip the
and add the header yourself:Authenticator ..header("Authorization", "Bearer " + token)
Retries and large responses
HttpClient503 Service Unavailable429 Too Many Requests
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.stream.Stream;
public class RetryAndStreaming {
// Retries 503 and 429 responses with exponential backoff; other statuses are returned
static HttpResponse<String> sendWithRetry(HttpClient c, HttpRequest req, int maxAttempts)
throws Exception {
long delay = 100;
for (int attempt = 1; ; attempt++) {
HttpResponse<String> r = c.send(req, HttpResponse.BodyHandlers.ofString());
boolean retryable = r.statusCode() == 503 || r.statusCode() == 429;
System.out.println(" attempt " + attempt + ": " + r.statusCode());
if (!retryable || attempt == maxAttempts) {
return r;
}
Thread.sleep(delay);
delay *= 2;
}
}
public static void main(String[] args) throws Exception {
TestServer ts = new TestServer();
try (HttpClient client = HttpClient.newHttpClient()) {
HttpResponse<String> r = sendWithRetry(client,
HttpRequest.newBuilder(URI.create(ts.url("/flaky"))).build(), 5);
System.out.println("result: " + r.statusCode() + " " + r.body());
// ofLines streams the body: lines are processed as they arrive
HttpResponse<Stream<String>> big = client.send(
HttpRequest.newBuilder(URI.create(ts.url("/big"))).build(),
HttpResponse.BodyHandlers.ofLines());
try (Stream<String> lines = big.body()) {
System.out.println("streamed lines: " + lines.count() + ", transfer-encoding: "
+ big.headers().firstValue("transfer-encoding").orElse("none"));
}
// Some headers are controlled by the client and cannot be set
try {
HttpRequest.newBuilder(URI.create(ts.url("/ping"))).header("Host", "evil.example");
} catch (IllegalArgumentException e) {
System.out.println("setting Host: IllegalArgumentException (" + e.getMessage()
+ ")");
}
}
ts.server.stop(0);
}
}
Output:
attempt 1: 503
attempt 2: 503
attempt 3: 200
result: 200 finally ok
streamed lines: 100000, transfer-encoding: chunked
setting Host: IllegalArgumentException (restricted header name: "Host")
- The request succeeded on attempt 3. Retry only idempotent requests (GET, PUT, DELETE) automatically; retrying a POST can create duplicates unless the API supports an idempotency key. In production, also add random jitter to the delay and honor a
header.Retry-After returns a stream that is filled as data arrives, so the 100,000 lines were never held in memory together. The server sent the body with chunked transfer encoding because its length was not known in advance. Close the stream, or the connection is not returned to the pool.BodyHandlers.ofLines() ,Host ,Connection and a few other headers are set by the client itself, and setting them throwsContent-Length .IllegalArgumentException
Concurrency, timeouts, redirects and request bodies
The test server's /slow
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.IntStream;
public class AsyncAndTimeouts {
public static void main(String[] args) throws Exception {
TestServer ts = new TestServer();
try (HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2)).build()) {
HttpRequest slow = HttpRequest.newBuilder(URI.create(ts.url("/slow"))).build();
// Ten slow requests one after another, then all at once with sendAsync
long t0 = System.nanoTime();
for (int i = 0; i < 10; i++) {
client.send(slow, HttpResponse.BodyHandlers.ofString());
}
System.out.printf("10 x /slow with send(): %5d ms%n",
(System.nanoTime() - t0) / 1000000);
t0 = System.nanoTime();
List<CompletableFuture<String>> futures = IntStream.range(0, 10)
.mapToObj(i -> client.sendAsync(slow, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body))
.toList();
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
System.out.printf("10 x /slow with sendAsync(): %5d ms, all \"%s\"%n",
(System.nanoTime() - t0) / 1000000, futures.get(0).join());
// A request timeout shorter than the server's 300 ms
HttpRequest impatient = HttpRequest.newBuilder(URI.create(ts.url("/slow")))
.timeout(Duration.ofMillis(100)).build();
try {
client.send(impatient, HttpResponse.BodyHandlers.ofString());
} catch (HttpTimeoutException e) {
System.out.println("timeout(100 ms): " + e.getClass().getSimpleName() + ": "
+ e.getMessage());
}
// Redirects are not followed unless the client is told to
HttpRequest old = HttpRequest.newBuilder(URI.create(ts.url("/old"))).build();
HttpResponse<String> r = client.send(old, HttpResponse.BodyHandlers.ofString());
System.out.println("default client: " + r.statusCode() + ", Location "
+ r.headers().firstValue("Location").orElse("-"));
try (HttpClient follower = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL).build()) {
HttpResponse<String> f = follower.send(old, HttpResponse.BodyHandlers.ofString());
System.out.println("Redirect.NORMAL: " + f.statusCode() + " \"" + f.body()
+ "\" from " + f.uri().getPath() + ", previous " + f.previousResponse()
.map(HttpResponse::statusCode).orElse(0));
}
// POST with a JSON body
HttpRequest post = HttpRequest.newBuilder(URI.create(ts.url("/echo")))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"Ana\"}")).build();
HttpResponse<String> created = client.send(post, HttpResponse.BodyHandlers.ofString());
System.out.println("POST: " + created.statusCode() + " " + created.body()
+ ", version " + created.version());
} finally {
ts.server.stop(0);
}
}
}
Output:
10 x /slow with send(): 3505 ms
10 x /slow with sendAsync(): 357 ms, all "slow answer"
timeout(100 ms): HttpTimeoutException: request timed out
default client: 301, Location /ping
Redirect.NORMAL: 200 "pong" from /ping, previous 301
POST: 201 POST application/json {"name":"Ana"}, version HTTP_1_1
- Ten blocking
calls took about 350 ms each: the 300 ms the server spends, plus a delayed-acknowledgment stall of about 40 ms on the reused connection that the next section explains, plus warm-up. Tensend calls ran concurrently and finished in about the time of one, because the client opened several connections and waited for all responses at once. On Java 21, tensendAsync calls on ten virtual threads achieve the same with blocking code.send on the request madetimeout(100 ms) throwsend after 100 ms. Without it, a request waits as long as the server takes. The client'sHttpTimeoutException only limits establishing the connection, so set both.connectTimeout- The default client returned the 301 and its
header instead of following it. WithLocation it fetchedRedirect.NORMAL , and/ping still shows the 301.previousResponse() never follows a redirect from HTTPS to HTTP;NORMAL does, which can leak data.ALWAYS sent the JSON, and the server saw theBodyPublishers.ofString header set by the code; the client does not set it for you. The response came back overContent-Type , as expected for plain HTTP; against an HTTPS server that supports it, the same code would reportHTTP_1_1 .HTTP_2
Body handlers, and what client reuse saves
The body handler decides where a response goes, which matters most for large bodies. The program fetches the 1 MB /big-Dsun.net.httpserver.nodelay=true
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.nio.file.Files;
import java.nio.file.Path;
public class HandlersAndCost {
public static void main(String[] args) throws Exception {
TestServer ts = new TestServer();
HttpRequest big = HttpRequest.newBuilder(URI.create(ts.url("/big"))).build();
try (HttpClient client = HttpClient.newHttpClient()) {
// Body handlers decide where the response goes
HttpResponse<String> asString = client.send(big, HttpResponse.BodyHandlers.ofString());
System.out.printf("ofString: %,d characters held in memory%n",
asString.body().length());
Path file = Files.createTempFile("big", ".txt");
HttpResponse<Path> toFile = client.send(big, HttpResponse.BodyHandlers.ofFile(file));
System.out.printf("ofFile: %,d bytes written to %s%n", Files.size(toFile.body()),
toFile.body().getFileName().toString().startsWith("big") ? "a temp file" : "?");
Files.delete(file);
HttpResponse<InputStream> stream = client.send(big,
HttpResponse.BodyHandlers.ofInputStream());
try (InputStream in = stream.body()) {
byte[] first = in.readNBytes(7);
System.out.println("ofInputStream: first bytes \"" + new String(first).trim()
+ "\", rest read on demand");
}
HttpResponse<Void> discarded = client.send(big,
HttpResponse.BodyHandlers.discarding());
System.out.println("discarding: status " + discarded.statusCode() + ", body "
+ discarded.body());
// What reusing one client saves: 300 small requests each way, after a warm-up
HttpRequest ping = HttpRequest.newBuilder(URI.create(ts.url("/ping"))).build();
for (int i = 0; i < 50; i++) {
client.send(ping, HttpResponse.BodyHandlers.ofString());
}
long t0 = System.nanoTime();
for (int i = 0; i < 300; i++) {
client.send(ping, HttpResponse.BodyHandlers.ofString());
}
long shared = System.nanoTime() - t0;
t0 = System.nanoTime();
for (int i = 0; i < 300; i++) {
try (HttpClient fresh = HttpClient.newHttpClient()) {
fresh.send(ping, HttpResponse.BodyHandlers.ofString());
}
}
long perRequest = System.nanoTime() - t0;
System.out.printf("shared client: %6.2f ms per request%n",
shared / 300 / 1e6);
System.out.printf("new client per request: %6.2f ms per request%n",
perRequest / 300 / 1e6);
} finally {
ts.server.stop(0);
}
}
}
Output of the handler and reuse run:
ofString: 1,088,895 characters held in memory
ofFile: 1,088,895 bytes written to a temp file
ofInputStream: first bytes "line 1", rest read on demand
discarding: status 200, body null
shared client: 1.19 ms per request
new client per request: 3.30 ms per request
held all 1,088,895 characters in memory, fine for JSON responses but not for downloads.ofString streamed the same bytes to disk,ofFile let the code read the first line and stop, andofInputStream threw the body away while still reading it, so the connection could be reused.discarding- A new client per request was two to five times slower than the shared one across runs, even on loopback with no TLS: each new client starts its own selector thread and opens a new TCP connection. Over the internet with HTTPS, the gap grows to tens or hundreds of milliseconds per request.
- A trap found while measuring: without the
property, the shared client took over 40 ms per request, slower than new clients. The JDK's built-innodelay writes response headers and body separately with Nagle's algorithm on, and on a reused connection the second write waits for a delayed acknowledgment. A new connection happened to avoid the delay. Production servers such as Netty, Tomcat and Jetty normally setHttpServer on their connections, so this is mainly a trap when testing against the JDK server; the effect is explained on theTCP_NODELAYTCP sockets page .
Production checklist
| Concern | Setting |
|---|---|
| Connection setup time | HttpClient.Builder.connectTimeout |
| Response time | HttpRequest.Builder.timeout |
| Redirects | followRedirects(Redirect.NORMAL)NEVER |
| Custom CAs or client certificates | sslContext(...) |
| Corporate proxy | proxy(ProxySelector.of(new InetSocketAddress(host, port))) |
| Threads for async callbacks | executor(...) |
| HTTP version | version(HttpClient.Version.HTTP_2)HTTP_1_1 |
| Retries | Your own code, for idempotent requests only, with backoff |
| Lifecycle | One shared client, closed at shutdown (Java 21+) |