【发布时间】:2014-09-06 00:52:45
【问题描述】:
我正在编写两个函数 - 第一个是登录某个站点,第二个是使用基于 cookie 的“登录”上下文获取主页。尽管 cookie 在第二种方法中可用(我使用 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 存储?为什么我无法获得“登录”版本的页面?
【问题讨论】:
标签: java cookies apache-httpclient-4.x