Lesson · Networking
The Modern HTTP Client (java.net.http): one client, multiplexed streams
15 min readModern HTTP Client
Java 11 put a real HTTP client in the JDK: HTTP/2 with multiplexing, CompletableFuture for async calls, streaming bodies, and one immutable HttpClient per application that owns the connection pool. This lesson covers the API and the behaviour behind it.
Why the JDK grew a new HTTP client
Every request on a fresh connection pays a TCP handshake and, over HTTPS, a TLS handshake before the first request byte leaves. On top of that cost, the pre Java 11 stack (HttpURLConnection) effectively gave you one request per connection, no HTTP/2, and an API that made streaming and timeouts awkward enough that teams reached for third-party clients by default.
Java 11 shipped java.net.http.HttpClient, and it answers all three problems at once: HTTP/2 with multiplexing, asynchronous calls through CompletableFuture, streaming request and response bodies, all in the JDK with no dependency needed for normal work.
The one thing to internalize before any API detail: HttpClient is immutable and expensive to build, because it owns a connection pool and an executor. Create one per application, share it, and never create one per request.
One client per application. A new HttpClient per call throws away pooling, repeats setup work and is the most common review comment on this API.
Building the client once
HttpClient.newBuilder() collects the choices that belong to the client: the connect timeout, the redirect policy, the executor that runs async callbacks, proxies, cookies and TLS material. build() returns an immutable client you keep for the lifetime of the process.
Defaults worth knowing: redirects are NEVER, so a 301 arrives as a response you handle yourself; the version is HTTP/2, attempted automatically when the server supports it. Whatever an implementation does about connect timeouts when you stay silent, set your own: waiting on a dead host is not a plan.
- `followRedirects(HttpClient.Redirect.NORMAL)` follows redirects except a downgrade from HTTPS to HTTP;
ALWAYSfollows everything;NEVERis the default and hands you the 3xx response. - `executor(Executor)` decides which threads run your
CompletableFuturecallbacks. Set it when you want bounded, named threads in your stack traces. - `proxy(ProxySelector)` and `authenticator(Authenticator)` route through proxies and answer 401 challenges, instead of hand-assembled headers.
- `cookieHandler(CookieHandler)` makes the client store and send cookies. Without one, only cookies you set as explicit request headers travel.
- `sslContext(...)` supplies the TLS configuration, which is the next lesson's topic. You rarely need to build one for a public endpoint.
Requests, publishers and handlers
HttpRequest.newBuilder(uri) takes what belongs to one request: a per-request timeout, headers, and the method. The body you send is a BodyPublisher (ofString, ofByteArray, ofFile, noBody, or ofInputStream for content you stream), and the body you accept is a BodyHandler (ofString, ofByteArray, ofFile, ofLines, ofInputStream).
A Response comes back for 404 and 500 just as readily as for 200: nothing throws on status codes, so response.statusCode() is a check you write yourself. Exceptions are transport-level: HttpTimeoutException and its subclass HttpConnectTimeoutException when a request or connect budget expires, ConnectException when the connection is refused, and plain IOException for everything else.
For large bodies the handler choice is the difference between streaming and an OutOfMemoryError: ofString materializes the entire payload, while ofLines() hands you a Stream<String> and ofInputStream() hands you an InputStream you consume as data arrives. ofInputStream() completes the response as soon as the headers are read, so you are reading the body while the server is still writing it, and ofLines() streams text the same way, one line at a time.
The status code is yours to check. The client reports the HTTP exchange faithfully; deciding that a 503 means failure is application policy, and it takes one line of code.
send, sendAsync, and who waits
send(request, handler) blocks the calling thread until the response is complete, then returns it. For a workflow that is naturally sequential (call A, read the answer, call B) that shape is honest and easy to read.
sendAsync(request, handler) returns a CompletableFuture<HttpResponse<...>> immediately and does not hold a thread per request while it travels; the client's own machinery waits on the network instead. That is what makes fan-out practical: fire N calls, combine them, and do not consume N threads while the round trips overlap.
- Fan-out in async:
CompletableFuture.allOforthenCombineover NsendAsynccalls is the pattern for aggregating several services into one response. - Sequential in sync: one call that must finish before the next one starts does not benefit from async; it just moves the error handling into a lambda.
- Same client either way: the client is immutable and thread-safe, so both styles share it, its pooled connections and its executor.
The question is never which style is faster. It is whether anything else can happen while this request travels; async exists for the yes case.
HTTP/2 multiplexing: many streams, one connection
In HTTP/1.1 a connection carries one request and its response at a time, and the next request waits. That is why clients opened pools of connections per host, and why pipelining, which promised to remove the wait, was abandoned in practice: responses still had to return in request order, so one slow response blocked everything queued behind it.
HTTP/2 splits each request into a stream identified by a stream id, and sends frames (headers, data) labelled with that id over a single TCP connection. Frames from different streams interleave freely while each stream's own frames keep their order, so a small response can complete while a large one is still streaming. Client-initiated streams use odd ids, and response.version() tells you whether HTTP/2 was actually negotiated.
One limit remains underneath: every stream shares the same TCP connection, so a lost packet stalls all of them until it is retransmitted. HTTP/3 over QUIC addresses exactly that by making streams independent at the transport layer too.
Multiplexing changes what a connection is: not one request at a time, but a shared pipe where many requests progress concurrently. That is also why you build one HttpClient and keep it.
Three GETs · one connection
The app builds one HttpClient and prepares three GETs to the same host: R1 /users (large), R2 /orders (small), R3 /stats. No connection exists yet; the client opens one when the first request is sent.
WebSocket: when messages go both ways
HTTP is request/response, so a server that must push needs polling or a second protocol. client.newWebSocketBuilder().buildAsync(uri, listener) gives you that second protocol over one connection: after an HTTP upgrade, either side can send messages at any time.
The listener receives onOpen, onText (and onBinary), onClose and onError, and it delivers messages under demand-based flow control: it is invoked for one message at a time and calls request(n) to receive more. The WebSocket has its own lifecycle, so you send with sendText and end with sendClose when the conversation is over.
A WebSocket is one connection with two directions and no request/response structure. Reconnection, heartbeats and backpressure are application work; the platform gives you the transport and ordered delivery.
Redirects, cookies, proxies: the client-level hooks
These behaviours belong to the client rather than to a request, and they are where HTTP hides its surprises. Redirects are not followed by default, so a 302 body reaches your JSON parser unless you set a policy. Cookies are stored only when you install a CookieHandler. Proxy selection and authentication challenges go through ProxySelector and Authenticator rather than hand-assembled headers.
The one value to verify rather than assume is the response version. The client attempts HTTP/2 by default, over TLS through ALPN and over plain HTTP through an upgrade, and falls back to HTTP/1.1 against servers that cannot do either, so response.version() is the ground truth for what happened on the wire.
- Redirects:
NEVER(default) hands you the 3xx;NORMALfollows everything except an HTTPS to HTTP downgrade;ALWAYSfollows everything. - Cookies: set
cookieHandler(new CookieManager())to persist and resend them. A per-request Cookie header works once but manages nothing. - Proxies and auth:
proxy(ProxySelector)andauthenticator(Authenticator)keep those concerns out of your request builders.
Check response.version() when HTTP/2 matters to you: negotiation is a suggestion the server can decline, and the fallback is silent.
A response arrived is not a request succeeded
Non-2xx statuses do not throw: 404, 409 and 503 arrive as normal responses, and code that assumes a parsed body misses them. The default redirect policy is NEVER, so a 302 body can reach the same parser. Check statusCode() before you trust the body, and decide your redirect policy explicitly instead of inheriting the default.
Interview angles
Why keep one HttpClient for the whole application?+
It is immutable and thread-safe, and it owns the connection pool and the executor. A client per request discards pooled connections, repeats setup and adds latency under load.
On Java 21 and later HttpClient is AutoCloseable, with close(), shutdown(), shutdownNow() and awaitTermination(), so a well-behaved service closes it once at shutdown instead of leaking the executor.
send versus sendAsync?+
send blocks the calling thread until the response is complete; sendAsync returns a CompletableFuture and does not consume a thread per request while the network does its work. Use async when other work can happen during the round trip, and sync when the workflow is strictly sequential.
Does a 404 throw?+
No. Status codes never throw; 4xx and 5xx are responses like any other, and you check statusCode() yourself. The exceptions you meet are transport-level: timeouts, refused connections and IO failures.
Common misconception: That an exception means the server answered with an error. A thrown exception means no complete response arrived, which is a different bug from a server that answered 503.
What does HTTP/2 multiplexing actually change?+
One TCP connection carries many concurrent streams, each identified by an id, and frames from different streams interleave on the wire. Responses complete in their own time instead of in request order, while order within each stream is preserved.
HTTP/1.1 serialized request/response pairs per connection, and pipelining failed because responses still had to return in request order. Head-of-line blocking at the TCP layer remains under HTTP/2 because all streams share one connection, and that is what HTTP/3 over QUIC removes.
How do you stream a large response?+
Use BodyHandlers.ofLines() or ofInputStream() instead of ofString(). With ofInputStream() the response completes once the headers are read, and you consume the body as it arrives; ofLines() streams lines the same way. Either choice keeps memory flat.
ofLines() returns a Stream<String> that you consume inside try-with-resources so the underlying connection is released. ofInputStream() is the escape hatch when you need bytes rather than text.
Follow-up: What breaks if you use ofString on a 2 GB body?
Where do cookies and redirects come from?+
Both are client-level settings. Redirects default to NEVER, so a 3xx reaches your code as a response; CookieHandler is what stores and resends cookies; Authenticator answers 401 challenges; ProxySelector routes through proxies.