Sub topic 3
Building a reusable HttpClient
This chapter assumes you know the three core types (HttpClient, HttpRequest, HttpResponse) and can send a basic GET with send. Here you will build one configured client and share it across your whole application.
Why the client is the expensive object
An HttpClient is more than a settings holder. It owns resources that are costly to create and valuable to keep:
- A pool of open connections to servers, so repeated calls to the same host skip the TCP and TLS handshakes.
- A selector thread that watches those connections for activity.
- An executor, which runs asynchronous work and completes the futures returned by
sendAsync. - Optional state such as a cookie handler, an authenticator and TLS settings.
Requests, by contrast, are cheap and immutable. The usual pattern is one long-lived client and a new request for every call.
The builder
You create a client with HttpClient.newBuilder(), set options, and call build(). The result is immutable, so you cannot change a setting later. If you need different settings, build a second client.
import java.net.http.HttpClient;
import java.time.Duration;
public class ClientDemo {
public static void main(String[] args) {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL)
.version(HttpClient.Version.HTTP_2)
.build();
System.out.println("Version: " + client.version());
System.out.println("Redirects: " + client.followRedirects());
System.out.println("Connect: " + client.connectTimeout().orElseThrow());
}
}The getters on the built client let you check what you configured. connectTimeout() returns an Optional<Duration> because the setting can be absent.
The settings you will use most
| Builder method | Default | What it controls |
|---|---|---|
| `connectTimeout(Duration)` | none (wait indefinitely) | How long to wait while establishing the connection. |
| `followRedirects(Redirect)` | `NEVER` | Whether 3xx responses are followed automatically. |
| `version(Version)` | `HTTP_2` | The protocol version requested first. |
| `executor(Executor)` | internal cached thread pool | Which threads run asynchronous tasks. |
| `proxy(ProxySelector)` | system default selector | Whether requests go through a proxy. |
| `cookieHandler(CookieHandler)` | none | Whether cookies are stored and replayed. |
| `authenticator(Authenticator)` | none | Credentials supplied when a server challenges. |
| `sslContext(SSLContext)` | default context | Trust stores and client certificates. |
The first three matter in almost every application, so they are covered here. The others appear in later chapters.
Connect timeout
With no connectTimeout, a request to an unreachable host can wait a very long time. Always set one. If it expires, send throws HttpConnectTimeoutException, a subclass of HttpTimeoutException. This timeout covers only connection setup. The per-request timeout on HttpRequest.Builder covers the wait for the response, and the next chapters cover it.
Redirect policy
Redirect has three values:
NEVERreturns the 3xx response to you as-is. This is the default, so a bare client will not follow a301or302.NORMALfollows redirects, except when they go from HTTPS to HTTP.ALWAYSfollows every redirect, including from HTTPS down to HTTP.
NORMAL is the safe choice for most programs. ALWAYS can silently drop you from an encrypted connection to a plain one.
Protocol version
version(HTTP_2) means "try HTTP/2 first". The client negotiates with the server and falls back to HTTP/1.1 when the server does not support HTTP/2. Setting HTTP_1_1 forces the older protocol. This is mostly useful when you debug a misbehaving server or proxy. To see which version was used, call response.version().
Sharing one client
Declare the client once and hand it to whatever needs it. A holder class is the simplest approach:
import java.net.http.HttpClient;
import java.time.Duration;
public final class Http {
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL)
.version(HttpClient.Version.HTTP_2)
.build();
private Http() {}
public static HttpClient client() {
return CLIENT;
}
}In a framework with dependency injection, expose the same client as a singleton bean instead of a static field. The effect is the same. HttpClient is thread-safe, so any number of threads can call send and sendAsync on it at once without locking.
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class UseShared {
public static void main(String[] args) throws Exception {
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
.GET()
.build();
HttpResponse<String> response =
Http.client().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " via " + response.version());
}
}Common errors
- Redirects seem to "fail". A bare client returns the
301or302and does not follow it. Your code then tries to parse an empty or HTML redirect body. SetfollowRedirects(NORMAL), or read theLocationheader yourself. - Hangs on unreachable hosts. No
connectTimeoutwas set. Setting it on the client applies it to every request. - Trying to change a client. There are no setters on a built client. Create a second client for requests that need different settings, such as a longer timeout or no redirects, and share both.
- Wrong assumptions about the executor. If you pass your own
executor, the client does not shut it down for you. A small fixed pool can also limit asynchronous throughput. For most programs the default is fine.
Exercise
A teammate writes a fetch(String url) helper that calls HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build() on every call. The helper is called 200 times a second. Name two problems this causes and the fix.
Show answer
Each call creates a new connection pool and its own threads, so connections are never reused. Every request pays for a new TCP and TLS handshake, which adds latency, and idle threads and sockets pile up under load. The fix is to build the client once, in a static field or a singleton bean, and have fetch use it. Only the HttpRequest should be created per call.
Exercise
You build a client with only connectTimeout(Duration.ofSeconds(3)) and request a URL that answers 301 Moved Permanently. What does response.statusCode() return, and which single builder call changes that?
Show answer
It returns 301, because the default redirect policy is NEVER. Adding followRedirects(HttpClient.Redirect.NORMAL) makes the client follow the redirect and return the final response.