Sub topic 19
Proxy, cookies, TLS and custom executors
This chapter covers the HttpClient.Builder options you need when a plain client isn't enough: corporate proxies, session cookies, private certificate authorities and your own thread pool. It assumes you can already build a client and send requests with send and sendAsync, and that you know the basics of CompletableFuture. All of these options are set on the builder, so they apply to every request the client sends.
Proxies
If you don't call proxy(...), the client uses ProxySelector.getDefault(). That selector reads the standard JVM system properties, such as http.proxyHost, http.proxyPort, https.proxyHost, https.proxyPort and http.nonProxyHosts. Environment variables like HTTPS_PROXY are not read.
To route all traffic through one proxy, build a selector from its address:
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.http.HttpClient;
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 8080)))
.build();ProxySelector.of(null) disables proxying and forces direct connections. For per-host rules, subclass ProxySelector and return a different List<Proxy> from select(URI).
Proxy authentication
When a proxy answers 407 Proxy Authentication Required, the client asks its Authenticator. Check getRequestorType() so you don't send proxy credentials to an origin server:
import java.net.Authenticator;
import java.net.PasswordAuthentication;
Authenticator proxyAuth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.PROXY) {
return new PasswordAuthentication(
"proxyuser", System.getenv("PROXY_PASSWORD").toCharArray());
}
return null;
}
};Pass it with .authenticator(proxyAuth).
Cookies
By default the client ignores cookies. A Set-Cookie header is visible in the response headers, but the client never sends it back. To get browser-like session handling, install a CookieManager:
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
CookieManager cookies = new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER);
HttpClient client = HttpClient.newBuilder()
.cookieHandler(cookies)
.build();
HttpRequest login = HttpRequest.newBuilder(URI.create("https://example.com/login"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString("user=ana&pass=secret"))
.build();
client.send(login, HttpResponse.BodyHandlers.discarding());
// The session cookie from the login response is now sent automatically.
HttpRequest profile = HttpRequest.newBuilder(URI.create("https://example.com/profile")).build();
HttpResponse<String> response = client.send(profile, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());The policies work like this:
| Policy | Behavior |
|---|---|
| `ACCEPT_ORIGINAL_SERVER` | Accepts cookies only from the server you requested. This is the `CookieManager` default policy and the usual choice. |
| `ACCEPT_ALL` | Accepts every cookie, including from third-party hosts. |
| `ACCEPT_NONE` | Stores nothing. |
Two points to remember. The store is in memory and disappears when the JVM exits. And a CookieManager is shared by every request on that client. If you serve several users from one process, give each user their own client, or you will mix their sessions. client.cookieHandler() returns an Optional<CookieHandler>, and cookies.getCookieStore().getCookies() lets you inspect what was stored.
TLS
The default client uses SSLContext.getDefault(). That context trusts the JDK's cacerts and negotiates the best protocol both sides support. You only customize it for two reasons: to trust a private certificate authority (CA), or to restrict protocols and cipher suites.
Trusting a private CA
Load your truststore, build a TrustManagerFactory, then create an SSLContext:
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
static SSLContext contextFrom(Path truststore, char[] password) throws Exception {
KeyStore ks = KeyStore.getInstance("PKCS12");
try (InputStream in = Files.newInputStream(truststore)) {
ks.load(in, password);
}
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
return context;
}This truststore replaces the default one. Public sites such as example.com are no longer trusted unless their CAs are also in your file. To keep the defaults, import your CA into a copy of cacerts.
Restricting protocols
sslParameters limits what the handshake may negotiate:
import javax.net.ssl.SSLParameters;
SSLParameters params = new SSLParameters();
params.setProtocols(new String[] {"TLSv1.3"});
HttpClient client = HttpClient.newBuilder()
.sslContext(contextFrom(Path.of("truststore.p12"), "changeit".toCharArray()))
.sslParameters(params)
.build();The client sets the ALPN protocol list itself, based on the HTTP version you chose, so don't try to set it here. After a response arrives, response.sslSession() returns an Optional<SSLSession>. It is empty for plain http:// requests. For HTTPS you can read getProtocol() and getPeerCertificates() to confirm what was negotiated.
Custom executors
The client runs its asynchronous work on an Executor. By default that is a cached thread pool owned by the client. Supply your own when you need to cap thread count, name threads for diagnostics, or run the work on a shared pool:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
AtomicInteger counter = new AtomicInteger();
ExecutorService pool = Executors.newFixedThreadPool(4, r -> {
Thread t = new Thread(r, "http-worker-" + counter.incrementAndGet());
t.setDaemon(true);
return t;
});
HttpClient client = HttpClient.newBuilder()
.executor(pool)
.build();
// ... use the client ...
pool.shutdown();Things to watch:
- You own the lifecycle of an executor you pass in. Shut it down when you are finished, or non-daemon threads will keep the JVM alive.
- Dependent stages such as
thenApplyrun on the thread that completes the previous stage. That is often an executor thread, so keep them short. UsethenApplyAsync(fn, yourOwnPool)for heavy work like parsing a large body. - A very small pool is not a request limit. It limits threads, not how many connections the client opens.
Exercise
A service handles requests for many users and calls an API that sets a session cookie at login. A developer creates one HttpClient with a CookieManager and shares it across all users. What goes wrong, and how do you fix it?
Show answer
Every user's requests share one cookie store, so a session cookie set for one user is sent on another user's requests. Sessions get mixed up and users can see each other's data. Fix it by creating a separate HttpClient and CookieManager per user, or by not using a CookieManager and setting the Cookie header explicitly on each request.
Exercise
You configure a client with a truststore containing only your company's internal CA. Calls to your internal API work, but calls to a public API now fail with a certificate error. Why, and what are two ways to fix it?
Show answer
A custom SSLContext built from your truststore replaces the JDK default truststore, so public CAs are no longer trusted. Either add the public CAs to your truststore (for example, by importing your CA into a copy of cacerts), or use two clients: one with the custom context for internal calls and one with the default context for public calls.