Skip to main content

Manage Cookies with Apache HttpClient

· One min read
Apache Wangye
Software developer and technical writer

Apache HttpClient can preserve cookies between requests through a shared CookieStore and request context.

CookieStore cookieStore = new BasicCookieStore();

try (CloseableHttpClient client = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build()) {

HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);

client.execute(new HttpGet("https://example.com/login"), context).close();
client.execute(new HttpGet("https://example.com/account"), context).close();
}

The store applies domain, path, expiry, secure, and policy rules. A cookie is not simply a name/value pair that should be sent to every host.

When persisting cookies across process restarts, protect session and authentication values as secrets, retain all required attributes, discard expired entries, and prevent cross-user mixing. Avoid logging complete cookies. Modern sites may also require CSRF tokens, redirects, JavaScript, or additional authentication state beyond cookies.

Page views: --

Total views -- · Visitors --