Skip to content

After upgrading to Apache HttpClient 4.4 it does not send cookies with requests

I am using the Apache HttpClient to send requests to our internal API servers. The servers require authentication and need a cookie to be set with an auth token.

Up to HttpClient 4.3.6 this has been working fine, but on 4.4 and above it has stopped sending the cookies on requests. My cookie domain is set to, which works for 4.3.6, but not 4.4 and above. If I’m more specific and give the full host as the cookie domain, i.e. it works, but this is not a solution.

Here’s a code snippet similar to what I’m doing:

public CloseableHttpResponse execute(CloseableHttpClient httpClient) throws IOException {
    BasicClientCookie cookie = new BasicClientCookie("cookieName", "myAuthtoken");
    HttpContext localContext = new BasicHttpContext(parentContext);
    CookieStore cookieStore = new BasicCookieStore();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    return httpClient.execute(target, request, localContext);

The httpClient is already constructed and passed into this code which sets the auth cookie.

I saw this, which is similar Cookies getting ignored in Apache httpclient 4.4, but in my case the cookies aren’t being sent to the server.

After turning on wire logging in the HttpClient I can see the following in 4.3.6, but not in 4.4 and above:

DEBUG [org.apache.http.client.protocol.RequestAddCookies] Cookie [version: 0][name: cookieName][value: authToken][domain:][path: /][expiry: Wed Jul 15 16:07:05 IST 2015] match []

Which leads me to think it’s something to do with cookie domain matching. Anyone have any ideas? Thanks.



I have debugged the example code. The problem is at BasicDomainHandler.match(Cookie, CookieOrigin) line: 129 as it expects org.apache.http.cookie.ClientCookie.DOMAIN_ATTR to be set in order to match full host name from URL to cookie domain. So you need to add the following line to your code, after you set the domain:

cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");

The change was added with revision 1646864 on 12/19/14, 10:59 PM:

RFC 6265 compliant cookie spec

4 People found this is helpful