A CookieHandler attached to HttpClient controls which cookies are accepted and sent. Sharing a client therefore shares session state as well as connection resources.
Java HttpClient cookies: make session storage an owned policy
Operational contract
A client created without a cookie handler does not provide an application cookie jar. If a workflow genuinely needs cookies, give that workflow its own CookieManager and client, then define its lifetime. The sample accepts cookies only from the original server according to CookiePolicy.ACCEPT_ORIGINAL_SERVER, but that rule is not a substitute for an application allowlist or secure transport. Keep credential-bearing workflows isolated; do not use one mutable cookie jar for unrelated tenants. Session teardown must clear or retire the jar according to the product's logout contract.
Failure case
A back-office tool has two warehouse accounts active in the same process. Giving both accounts one client with one cookie manager could mix their login state. The factory creates one jar per account session. The owner stores the resulting client only within that session and discards it on logout, instead of putting it in a global singleton.
Java code
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.http.HttpClient;
public class WarehouseSessionClient {
public static HttpClient forOneSession() {
CookieManager sessionCookies = new CookieManager();
sessionCookies.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
return HttpClient.newBuilder()
.cookieHandler(sessionCookies)
.followRedirects(HttpClient.Redirect.NEVER)
.build();
}
}Performance and ownership cost
A cookie jar retains state proportional to accepted cookies; request matching also costs work proportional to the store contents. One client per session uses more connection resources than one global client, so cap session count and retire idle sessions. Isolation is the reason to pay that cost.
Common Mistakes
- Do not share one cookie jar across unrelated user sessions.
- Do not assume a client without a handler persists cookies.
- Do not call an origin cookie policy a complete authorization rule.
Connected lessons
- Java HttpClient: request policy, deadlines, and response size
- Java HttpClient redirects: check the next origin before resending
- Java HTTP query values: encode data without changing URI structure
- Java HttpClient deadlines: separate connection and request timeouts
- Java streaming HTTP bodies: close the stream and cap retained bytes
- Java Retry-After: parse a bounded server delay without inventing a retry
- Java HTTP and fork/join decisions quiz
- Advanced Java
