barunsthakur
barunsthakur

Reputation: 1216

Cookies getting ignored in Apache httpclient 4.4

I upgraded Apache http client from 4.3.6 to 4.4 and observed that cookies are getting ignored. Any idea how to get cookie working in 4.4?

Edit: code snippet

CookieStore cookieStore = new BasicCookieStore();
cookieStore.addCookie(new BasicClientCookie("name", "value"));
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
HttpClient client = HttpClientBuilder.create()
    .disableRedirectHandling()
    .setDefaultRequestConfig(config)
    .setDefaultCookieStore(cookieStore)
    .build();

I tried CookieSpecs.DEFAULT, CookieSpecs.STANDARD and CookieSpecs.STANDARD_STRICT but none seem to work.

Upvotes: 2

Views: 8185

Answers (2)

Anton Krosnev
Anton Krosnev

Reputation: 4122

I have executed the example code with both versions 4.3.6 and 4.5 . With 4.3.6 I used RequestConfig.DEFAULT and it was working fine. With 4.5 it returns

java.lang.NullPointerException: while trying to invoke the method java.lang.String.equalsIgnoreCase(java.lang.String) of a null object loaded from local variable 'domain'
at org.apache.http.impl.cookie.PublicSuffixDomainFilter.match(PublicSuffixDomainFilter.java:76)
at org.apache.http.impl.cookie.CookieSpecBase.match(CookieSpecBase.java:135)
at org.apache.http.impl.cookie.DefaultCookieSpec.match(DefaultCookieSpec.java:177)
at org.apache.http.client.protocol.RequestAddCookies.process(RequestAddCookies.java:165)

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

RFC 6265 compliant cookie spec

In order to make things work with version 4.5 you will need to set domain to the cookie and it the domain does not equal the exact host also org.apache.http.cookie.ClientCookie.DOMAIN_ATTR must be set:

    BasicClientCookie cookie = new BasicClientCookie("cookieName", "cookieValue");
    cookie.setDomain(".my.domain.com");
    cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(cookie);

Upvotes: 5

ok2c
ok2c

Reputation: 27538

The cookie from your sample app gets matched to the cookie origin by both the default and the standard policies. I doubt this is an HttpClient issue.

BasicClientCookie cookie = new BasicClientCookie("name", "value");
cookie.setDomain("0.0.0.0");

CookieOrigin cookieOrigin = new CookieOrigin("0.0.0.0", 8000, "/", false);

DefaultCookieSpec defaultCookieSpec = new DefaultCookieSpec();
System.out.println("Default policy match :" + defaultCookieSpec.match(cookie, cookieOrigin));

RFC6265LaxSpec standardCookieSpec = new RFC6265LaxSpec();
System.out.println("Standard (RFC 6265) policy match :" + standardCookieSpec.match(cookie, cookieOrigin));

Use wire logging to see exactly what kind of cookie header(s) get generated by HttpClient

Upvotes: 0

Related Questions