How to Use Cookies in Java HTTP Requests
In this article
Cookies are small pieces of data that servers send to a client (like a browser or a Java application) to remember stateful information, such as session IDs or user preferences. In Java, when you make HTTP requests using the built-in HttpURLConnection or the newer java.net.http.HttpClient, you need to manually manage cookies—there is no automatic cookie jar like in a browser. This guide shows you how to capture cookies from a response, store them, and send them back in subsequent requests, enabling session persistence and authenticated access.
What You'll Need
- Java Development Kit (JDK) 8 or later (for
HttpURLConnection) or JDK 11+ (forjava.net.http.HttpClient). - A basic understanding of HTTP requests and responses.
- A text editor or IDE (like IntelliJ IDEA, Eclipse, or VS Code).
Step-by-Step
- Choose your HTTP client. For modern Java, use
java.net.http.HttpClient(JDK 11+). For older projects,HttpURLConnectionworks but requires more boilerplate. This guide focuses onHttpClientbecause it's cleaner and supports HTTP/2. - Create an HttpClient instance. You can reuse the same client for multiple requests. Optionally, set a cookie handler (see step 7) to automate cookie management.
- Send your first request. Build an
HttpRequestwith the target URL and method (GET, POST, etc.). Send it usingclient.send()(synchronous) orclient.sendAsync()(asynchronous). The response will contain aSet-Cookieheader (or multiple) if the server wants to set cookies. - Extract cookies from the response. Get the
HttpHeadersfrom the response object. Callheaders().allValues("Set-Cookie")to get a list of cookie strings. Each string looks likename=value; Path=/; HttpOnly. You only need thename=valuepart for sending back. - Store cookies in a map. Use a
Map<String, String>to store cookie names and values. Parse each Set-Cookie string by splitting on ';' and then on '='. Be careful with values that contain '=' (unlikely but possible). A simple approach: split on ';', take the first part, then split on '=' with a limit of 2. - Build the next request with cookies. When making subsequent requests, add a
Cookieheader. The value is a semicolon-separated list ofname=valuepairs, e.g.,sessionId=abc123; theme=dark. Set this header on yourHttpRequest.Builderusing.header("Cookie", cookieString). - Optionally, use a CookieHandler for automation. Java provides
java.net.CookieManagerandjava.net.CookieHandler. You can set a default cookie handler on theHttpClientviaHttpClient.newBuilder().cookieHandler(new CookieManager()).build(). This handler automatically stores cookies from responses and adds them to subsequent requests. However, it's not perfect for all cases (e.g., it may ignore some attributes), so manual handling is often more predictable. - Test with a real session. Use a website that requires login (e.g., a test API that returns a session cookie). Send a login request, capture the session cookie, then send a request to an authenticated endpoint using that cookie. Verify the response contains the expected data.
Common Mistakes
- Not parsing the Set-Cookie header correctly. The header can contain multiple cookies separated by commas, and each cookie has attributes like
ExpiresorSecure. If you split by ';' naively, you might include attributes as cookie names. Always take only the first part before the first ';'. - Forgetting to send cookies on redirects. If the server redirects (HTTP 302), the
HttpClientfollows redirects by default, but it may not forward the Cookie header automatically unless you handle it. Set.followRedirects(HttpClient.Redirect.NORMAL)and ensure your cookie header is set on the original request; the client will propagate it. - Using a new HttpClient instance for each request. If you rely on the built-in cookie handler, each new client has its own cookie jar. Reuse the same client instance for a session.
- Not URL-encoding cookie values. If a cookie value contains characters like spaces or semicolons, they should be percent-encoded. Use
URLEncoder.encode(value, StandardCharsets.UTF_8)when storing, and decode when reading.
Tips
- For debugging, print the
Set-Cookieheaders and theCookieheader you send. This helps verify what the server expects. - If you need to handle multiple cookies with the same name (rare), store them in a list per name.
- Consider using a library like Apache HttpClient or OkHttp if you need advanced cookie management (e.g., persistent storage, domain/path matching). They handle cookies out of the box.
- When using
CookieManager, you can set a customCookiePolicyto accept all cookies, which is useful for testing. - For secure cookies (with
Secureattribute), ensure you're using HTTPS; otherwise, the cookie handler may not store them.
Troubleshooting
- Server returns 401 Unauthorized even after sending cookies. Check if the cookie name/value is correct. Some servers use a session token in the URL or a header instead. Also, verify that the cookie is being sent on the correct path (the server may set a Path attribute).
- Cookies are not being stored. If you're using
CookieManager, ensure you've set it on the client builder. Also, check that the server'sSet-Cookieheader is not malformed (e.g., missing '='). - Cookie value contains special characters. Some servers encode cookies with base64 or JSON. If you see unexpected characters, try URL-decoding the value before sending back.
- Redirects lose cookies. If your client follows a redirect to a different domain, the cookie may not be sent due to security policies. Handle redirects manually by checking the
Locationheader and re-adding cookies if the domain matches. - HttpClient throws
IllegalArgumentExceptionfor restricted header. TheCookieheader is a restricted header in some contexts. If you get an error, useSystem.setProperty("jdk.httpclient.allowRestrictedHeaders", "cookie")before creating the client.
Frequently Asked Questions
Can I use cookies with HttpURLConnection?
Yes. You can read the Set-Cookie header from the response and set the Cookie header on the next request. It's more manual, but the same principles apply.
Do I need to handle cookie expiration?
If you manually store cookies, you should check the Expires or Max-Age attribute and remove expired cookies. The built-in CookieManager does this automatically.
What is the difference between session cookies and persistent cookies?
Session cookies are not stored on disk and are deleted when the client closes. Persistent cookies have an Expires or Max-Age attribute. In Java, the CookieManager stores both in memory unless you provide a persistent store.
Can I send cookies from a file to simulate a browser session?
Yes. Read the cookies from a file (e.g., in Netscape format) and add them to the request header. Tools like curl use this format, and you can parse it similarly.
Why does the server not recognize my cookie?
Check the domain and path of the cookie. If the server set Path=/app, sending it to /other won't work. Also, ensure the cookie name is exactly as sent.
Is it safe to store cookies in plain text?
If the cookies contain sensitive session tokens, store them securely (e.g., encrypted or in a protected file). Avoid logging them.