java - HttpClient没有将所有cookie发送到restful api
问题描述
我正在使用 HttpClient 4.4.1 调用一个 restful api,但它没有发送 cookie,
private CloseableHttpResponse call(String url, javax.servlet.http.HttpServletRequest httpServletRequest) {
HttpGet request = new HttpGet(url);
BasicHttpContext localContext = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
javax.servlet.http.Cookie[] cookies = httpServletRequest.getCookies();
BasicClientCookie basicClientCookie = null;
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
javax.servlet.http.Cookie cookie = cookies[i];
basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
basicClientCookie.setDomain(cookie.getDomain());
basicClientCookie.setPath("/");
basicClientCookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
basicClientCookie.setVersion(0);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 100);
Date date = calendar.getTime();
basicClientCookie.setExpiryDate(date);
cookieStore.addCookie(basicClientCookie);
}
}
if (cookieStore.getCookies() != null) {
System.out.println("Cookies size " + cookieStore.getCookies().size());
}
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(request, localContext);
} catch (IOException e) {
System.out.println("msg " + e.getMessage());
}
return httpResponse;
}
我可以看到它只发送已添加的最后一个 cookie。我错过了什么?请帮忙。
解决方案
问题肯定在 for 循环内的代码中,因为只有最后添加的 cookie 是可见的。
尝试使用调试器调试 for 循环,或者system.out.println
在从请求中获取 cookies 数组时在循环之前添加语句,而不是在创建基本客户端 cookie 时在循环内,然后在添加基本客户端 cookie 之前和之后cookiestore
正如评论中所建议的,您也没有添加cookiestore
到上下文中。
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
上面代码的另一个问题是
basicClientCookie.setDomain(cookie.getDomain());
cookie.getDomain()
和 urlrequest
可以不同,根据 cookie 的行为,它们应该是相同的,那么只有 cookie 会发送。所以只有具有相同 url 的 cookie 才会随请求一起发送
推荐阅读
- tensorflow - 在 keras 中实现共享权重
- swiftui - 当 TabView 内的 NavigationView 时,SwiftUI onAppear 调用了两次
- matlab - Matlab - 计算间隔时间内产生的所有分子的总和
- qt - Qt Quick2 Material Dark Theme 看起来有问题/不可读
- java - 如何合并具有不同变量类型的两个列表
- javascript - lodash过滤对象数组并分组创建一个新数组
- sql-server - 从另一台计算机连接到 SQL Server - SQL 网络实例相关问题(错误 258)
- hyperledger-fabric - 如何构建定时链码?
- flutter - flutter 简单计算 函数错误
- spring-data-mongodb - 为什么spring data不记录声明为Object的字段的运行时类型?