我正在使用 Apache HttpClient 向我们的内部 API 服务器发送请求。服务器需要身份验证,并且需要使用身份验证 token 设置 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 已经构建并传递到设置身份验证 cookie 的代码中。
我看到了这个,类似Cookies getting ignored in Apache httpclient 4.4 ,但在我的例子中,cookie 没有被发送到服务器。
在 HttpClient 中打开 wire logging 后,我可以在 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 域匹配有关。有人有主意吗?谢谢。
最佳答案
我已经调试了示例代码。问题出在 BasicDomainHandler.match(Cookie, CookieOrigin) line: 129
因为它希望设置 org.apache.http.cookie.ClientCookie.DOMAIN_ATTR 以匹配从 URL 到 cookie 域的完整主机名。因此,您需要在设置域后将以下行添加到您的代码中:
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
更改是在 2014 年 12 月 19 日晚上 10:59 通过修订版 1646864 添加的:
RFC 6265 compliant cookie spec
关于java - 升级到 Apache HttpClient 4.4 后,它不会发送带有请求的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31412584/