Cookies getting ignored in Apache httpclient 4.4

房东的猫 提交于 2020-01-04 15:57:14

问题


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.


回答1:


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);



回答2:


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



来源:https://stackoverflow.com/questions/29970409/cookies-getting-ignored-in-apache-httpclient-4-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!