Zimt

How to Use Cookies in Java HTTP Requests

· 5 min read · Cookies and Bars

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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+ (for java.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

  1. Choose your HTTP client. For modern Java, use java.net.http.HttpClient (JDK 11+). For older projects, HttpURLConnection works but requires more boilerplate. This guide focuses on HttpClient because it's cleaner and supports HTTP/2.
  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.
  3. Send your first request. Build an HttpRequest with the target URL and method (GET, POST, etc.). Send it using client.send() (synchronous) or client.sendAsync() (asynchronous). The response will contain a Set-Cookie header (or multiple) if the server wants to set cookies.
  4. Extract cookies from the response. Get the HttpHeaders from the response object. Call headers().allValues("Set-Cookie") to get a list of cookie strings. Each string looks like name=value; Path=/; HttpOnly. You only need the name=value part for sending back.
  5. 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.
  6. Build the next request with cookies. When making subsequent requests, add a Cookie header. The value is a semicolon-separated list of name=value pairs, e.g., sessionId=abc123; theme=dark. Set this header on your HttpRequest.Builder using .header("Cookie", cookieString).
  7. Optionally, use a CookieHandler for automation. Java provides java.net.CookieManager and java.net.CookieHandler. You can set a default cookie handler on the HttpClient via HttpClient.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.
  8. 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 Expires or Secure. 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 HttpClient follows 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-Cookie headers and the Cookie header 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 custom CookiePolicy to accept all cookies, which is useful for testing.
  • For secure cookies (with Secure attribute), 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's Set-Cookie header 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 Location header and re-adding cookies if the domain matches.
  • HttpClient throws IllegalArgumentException for restricted header. The Cookie header is a restricted header in some contexts. If you get an error, use System.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.