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.

Share

Contents

How java.net.http.HttpClient works

HttpClient (Java 11, JEP 321) replaced HttpURLConnection as the JDK's HTTP API. It is built from three immutable pieces: an HttpClient holding configuration and a pool of connections, an HttpRequest describing one request, and a body handler that decides how the response body is consumed, as a String, a file, a stream of lines or raw bytes. Underneath, the client is asynchronous: it runs its own selector thread and non-blocking sockets, and the blocking send is a wait on the same machinery that sendAsync exposes as a CompletableFuture.

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.

Java's HTTP client APIs
APISinceNotes
HttpURLConnectionJava 1.1Blocking, HTTP/1.1 only, awkward API; still found in old code
HttpClientJava 11 (JEP 321)HTTP/2, async, WebSocket, immutable builders
HttpClient.close()Java 21The client is AutoCloseable and can be shut down
HTTP/3Java 26 (JEP 517)Opt-in: set HttpClient.Version.HTTP_3 on the client or the request; it falls back to HTTP/2 when the server does not support 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 and bound to the loopback address. It records the client port of each request (one port per TCP connection), demands Basic authentication on /secure, sets a cookie on /login, fails twice on /flaky and streams 100,000 lines from /big. For the basic request and response API, see Java HttpClient.

Java
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 keeps a pool of open connections and reuses them for later requests to the same server. The program sends 10 requests through one shared client, then 10 requests each through a new client, and counts how many TCP connections the server saw.

Java
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:

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 per application (or per configuration) and share it; it is thread-safe. With HTTP/2, which the client negotiates automatically over TLS when the server supports it, concurrent requests to one server are multiplexed over a single connection.

Authentication and cookies

Two client-level features handle state across requests:

  • An Authenticator supplies credentials when a server answers 401 with a WWW-Authenticate challenge. The client then repeats the request with an Authorization header.
  • A CookieHandler, usually CookieManager, stores cookies from Set-Cookie headers and sends them back on matching requests.

The program calls the protected endpoint and the login/profile pair with and without each feature.

Java
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:

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 HttpClient keeps no cookies, so the session cookie from /login was lost. With a CookieManager, it was stored and sent on the next request.
  • For bearer tokens (OAuth, JWT), skip the Authenticator and add the header yourself: .header("Authorization", "Bearer " + token).

Retries and large responses

HttpClient never retries based on status codes; that is the application's decision. The helper below retries 503 Service Unavailable and 429 Too Many Requests with exponential backoff (100 ms, then 200 ms, and so on). The flaky endpoint fails twice, so the third attempt should succeed. The program then streams a large response and tries to set a header the client controls.

Java
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:

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 Retry-After header.
  • BodyHandlers.ofLines() 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.
  • Host, Connection, Content-Length and a few other headers are set by the client itself, and setting them throws IllegalArgumentException.

Concurrency, timeouts, redirects and request bodies

The test server's /slow endpoint takes 300 ms, like a slow backend. The program calls it ten times in sequence and ten times concurrently, gives one request a shorter timeout than the server needs, follows a 301 redirect, and posts a JSON body.

Java
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:

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 send 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. Ten sendAsync 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, ten send calls on ten virtual threads achieve the same with blocking code.
  • timeout(100 ms) on the request made send throw HttpTimeoutException after 100 ms. Without it, a request waits as long as the server takes. The client's connectTimeout only limits establishing the connection, so set both.
  • The default client returned the 301 and its Location header instead of following it. With Redirect.NORMAL it fetched /ping, and previousResponse() still shows the 301. NORMAL never follows a redirect from HTTPS to HTTP; ALWAYS does, which can leak data.
  • BodyPublishers.ofString sent the JSON, and the server saw the Content-Type header set by the code; the client does not set it for you. The response came back over HTTP_1_1, as expected for plain HTTP; against an HTTPS server that supports it, the same code would report 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 response four ways, then times 300 small requests through one shared client and through a new client per request, after 50 warm-up requests. The test server runs with -Dsun.net.httpserver.nodelay=true, for a reason explained below; the timings are a rough loopback measurement on a 2-CPU Linux machine.

Java
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:

Output
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
  • ofString held all 1,088,895 characters in memory, fine for JSON responses but not for downloads. ofFile streamed the same bytes to disk, ofInputStream let the code read the first line and stop, and discarding threw the body away while still reading it, so the connection could be reused.
  • 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 nodelay property, the shared client took over 40 ms per request, slower than new clients. The JDK's built-in HttpServer 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 set TCP_NODELAY on their connections, so this is mainly a trap when testing against the JDK server; the effect is explained on the TCP sockets page.

Production checklist

HttpClient settings worth setting explicitly
ConcernSetting
Connection setup timeHttpClient.Builder.connectTimeout
Response timeHttpRequest.Builder.timeout on every request
RedirectsfollowRedirects(Redirect.NORMAL) if wanted; the default is NEVER
Custom CAs or client certificatessslContext(...); see SSL/TLS sockets
Corporate proxyproxy(ProxySelector.of(new InetSocketAddress(host, port)))
Threads for async callbacksexecutor(...); the default is a cached thread pool
HTTP versionversion(HttpClient.Version.HTTP_2) is the default preference; force HTTP_1_1 for servers with broken HTTP/2
RetriesYour own code, for idempotent requests only, with backoff
LifecycleOne shared client, closed at shutdown (Java 21+)