Apache HttpClient: Get Cookies From Response
In this article
To get cookies from an Apache HttpClient response, you access the Set-Cookie headers directly from the response object, or use the built-in cookie store to retrieve them automatically. The most reliable method is using the HttpClientContext and its associated CookieStore, which collects cookies sent by the server during the request. This guide shows both approaches, with code examples you can adapt to your project.
What You'll Need
- Apache HttpClient library (version 4.x or 5.x) added to your project dependencies.
- A basic understanding of Java and HTTP requests.
- An IDE or text editor to write and run your code.
Step-by-Step
Method 1: Using the CookieStore (Recommended)
- Create an HttpClient instance. Use
HttpClients.createDefault()for a standard client, or build a custom one withHttpClientBuilderif you need specific configuration. - Create an HttpClientContext. This context holds the cookie store. Instantiate it with
HttpClientContext.create(). - Execute your request. Pass the context to the
execute()method. For example:CloseableHttpResponse response = httpClient.execute(request, context); - Retrieve the cookie store from the context. After the response is received, call
context.getCookieStore()to get theCookieStoreobject. - Get the cookies. Call
cookieStore.getCookies()which returns aList<Cookie>. EachCookieobject has methods likegetName(),getValue(),getDomain(), andgetPath(). - Iterate and use the cookies. Loop through the list and extract the values you need. Remember to close the response in a
finallyblock to release resources.
Method 2: Directly from Response Headers
- Execute the request normally. Use
CloseableHttpResponse response = httpClient.execute(request); - Get all headers named "Set-Cookie". Call
response.getHeaders("Set-Cookie")which returns an array ofHeaderobjects. - Parse each header value. Each header's value is a string like
sessionId=abc123; Path=/; HttpOnly. You need to split on;and then on=to get the name and value. Be careful to ignore attributes likePath,Domain,Expires, etc. - Handle multiple cookies. A server can send multiple
Set-Cookieheaders in one response. Iterate through all of them.
Common Mistakes
- Not closing the response. Forgetting to call
response.close()leads to connection leaks and resource exhaustion. - Using the wrong HttpClient version. In HttpClient 5.x, some classes moved to different packages (e.g.,
org.apache.hc.client5.http). Make sure your imports match your dependency version. - Assuming cookies are always present. The server may not send any cookies, so your code should handle an empty list or null gracefully.
- Parsing Set-Cookie manually incorrectly. Cookie values can contain
=or;characters. Use a proper parser likeorg.apache.http.client.utils.DateUtilsor better, rely on the cookie store. - Reusing the same context without clearing. If you reuse an
HttpClientContextfor multiple requests, cookies accumulate. CallcookieStore.clear()if you need a fresh state.
Tips
- Prefer the CookieStore approach. It handles all the parsing, expiry, and domain matching for you. It's the intended way in HttpClient.
- Set a custom CookieStore if needed. You can create your own
CookieStoreimplementation and set it on the context before executing the request. - Use the
BasicCookieStore. For most cases,new BasicCookieStore()and assign it to the context withcontext.setCookieStore(store)works well. - Check response status first. Only attempt to read cookies if the response status code is 2xx or 3xx. A 4xx/5xx may not contain meaningful cookies.
- For HttpClient 5.x, use
HttpClientContextfromorg.apache.hc.client5.http.protocol.
Troubleshooting
- No cookies in the store. Verify that the server actually sends cookies. Use a tool like curl or browser dev tools to check. Also, ensure you are not redirecting away from the cookie-setting domain.
- Cookies not persisting between requests. You must reuse the same
HttpClientContext(or copy the cookie store) across requests. Creating a new context each time loses the cookies. - ClassNotFoundException for CookieStore. This usually means you have the wrong HttpClient version. For version 4.x, it's
org.apache.http.client.CookieStore; for 5.x, it'sorg.apache.hc.client5.http.cookie.CookieStore. - Cookie values are URL-encoded. Some cookies contain special characters. Use
URLDecoder.decode()if you manually parse them, but the cookie store already decodes. - Getting a null context. If you didn't pass the context to
execute(), the context you created won't be populated. Always pass the same context object.
Frequently Asked Questions
Can I get cookies from a redirect response?
Yes, but you need to enable redirect handling. By default, HttpClient follows redirects automatically, and cookies set during the redirect chain are stored in the context. If you disable redirects, you'll only get the first response's cookies.
How do I send cookies back in subsequent requests?
Reuse the same HttpClientContext or set the cookie store on the new context. HttpClient automatically adds stored cookies to outgoing requests if the domain and path match.
What if the server sends multiple cookies with the same name?
The cookie store will keep both if they have different paths or domains. If they are identical, the latest one typically overwrites the older one.
Is it safe to parse Set-Cookie headers manually?
It is possible but error-prone. Cookie attributes can be in any order, and values may contain semicolons. Use the cookie store to avoid bugs.
How do I clear cookies from the store?
Call cookieStore.clear() on the store retrieved from the context. This removes all cookies.
Does the cookie store work with HTTPS?
Yes, it works over HTTPS without any extra configuration. The cookies are stored and sent encrypted.