[英]HttpClient - can't access cookies in GET method
我正在编写两个功能-第一个功能用于登录某个网站,第二个功能使用基于Cookie的“已登录”上下文来获取主页。 尽管存在cookie在第二种方法中可用的事实(我使用HttpClientContext.getCookieStore().getCookies()
提取了它们,并且它们似乎还可以HttpClientContext.getCookieStore().getCookies()
,但主页似乎仍在为非登录用户显示其版本。
用于登录网站的代码:
// Prepare cookie store
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
CookieStore cookieStore = new BasicCookieStore();
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
// Prepare http Client
CloseableHttpClient httpclient = HttpClients
.custom()
.setDefaultRequestConfig(globalConfig)
.setDefaultCookieStore(cookieStore)
.build();
// Prepare post for login page
HttpPost httpPost = new HttpPost("http://somesite/login");
// Prepare nvps store
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("login", "***"));
nvps.add(new BasicNameValuePair("passwd", "***"));
// Set proper entity
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
} finally {
response.close();
}
用于获取主页内容的代码(URIBuilder作为参数传递):
// Build URI
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
// Prepare cookie store
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
CookieStore cookieStore = new BasicCookieStore();
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
// Prepare http Client
CloseableHttpClient httpclient = HttpClients
.custom()
.setDefaultRequestConfig(globalConfig)
.setDefaultCookieStore(cookieStore)
.build();
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String entityContents = "";
int respCode = response.getStatusLine().getStatusCode();
if (entity != null) {
entityContents = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
}
httpclient.close();
我的GET请求使用cookie存储吗? 为什么我无法获得页面的“登录”版本?
解决方案非常简单-httpclient并未使用任何默认的内存存储来存储Cookie,并且我错误地假设它具有某些存储空间。
当我在侧面存储cookie(并对其进行序列化),然后-通过反序列化cookie启动GET请求时,一切正常。
因此,在POST请求(登录)之后:
CookieStore cookieStore = httpClient.getCookieStore();
List<Cookie> cookies = cookieStore.getCookies();
然后-以某种方式序列化该列表。 在执行GET请求时:
CookieStore cookieStore = new BasicCookieStore();
for(int i =0;i<cookies.length;i++) {
cookieStore.addCookie(cookies[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.