在升级到Apache HttpClient 4.4后,它不发送请求的cookie

问题描述 投票:6回答:2

我正在使用Apache HttpClient向我们的内部API服务器发送请求。这些服务器需要认证,并且需要一个cookie来设置一个认证令牌。

在HttpClient 4.3.6之前,这个功能一直都很好,但是在4.4及以上的版本中,它已经停止了发送请求的cookie。我的cookie域名设置为.subdomain.mycompany.com,这在4.3.6上能用,但在4.4及以上就不行了。如果我更具体地给出完整的主机作为cookie域,即host.subdomain.mycompany.com,它可以工作,但这不是一个解决方案。

下面是一个与我所做的类似的代码片段。

public CloseableHttpResponse execute(CloseableHttpClient httpClient) throws IOException {
    BasicClientCookie cookie = new BasicClientCookie("cookieName", "myAuthtoken");
    cookie.setPath("/");
    cookie.setDomain(".subdomain.mycompany.com");
    cookie.setSecure(false);
    HttpContext localContext = new BasicHttpContext(parentContext);
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(cookie);
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    return httpClient.execute(target, request, localContext);
}

httpClient已经被构造出来了 然后传入这段代码,设置了Auth Cookie。

我看到了这个,这也是类似的 在Apache httpclient 4.4中,Cookies被忽略了。但在我的情况下,Cookies并没有被发送到服务器上。

在HttpClient中打开线程日志后,我可以在4.3.6中看到以下内容,但在4.4及以上版本中却没有。

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

这让我觉得这和cookie的域名匹配有关。谁有什么想法?谢谢,我使用的是Apache HttpClient。

java cookies apache-httpclient-4.x
2个回答
8
投票

我已经调试了示例代码。问题出在 BasicDomainHandler.match(Cookie, CookieOrigin) line: 129 果然 org.apache.http.cookie.ClientCookie.DOMAIN_ATTR 来设置,以便从URL到cookie域名的全主机名匹配。所以你需要在设置域名后,在你的代码中添加以下一行。

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

这个改动是在121914年10月59日下午的1646864次修订中添加的。

RFC 6265兼容的cookie规范


0
投票

按照另一个答案的建议,设置这样的东西应该可以解决。

cookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".subdomain.mycompany.com");

设置的必要性 ClientCookie.DOMAIN_ATTR 是记载在 HTTP组件 第3章. HTTP状态管理:

下面是一个创建客户端cookie对象的例子。

BasicClientCookie cookie = new BasicClientCookie("name", "value");
// Set effective domain and path attributes
cookie.setDomain(".mycompany.com");
cookie.setPath("/");
// Set attributes exactly as sent by the server
cookie.setAttribute(ClientCookie.PATH_ATTR, "/");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".mycompany.com");
© www.soinside.com 2019 - 2024. All rights reserved.