如何从httpclient获取cookie?

时间:2014-06-06 14:20:30

标签: android cookies apache-httpclient-4.x

我使用httppost登录bbs。 httpclient可以自动保存cookie和其他信息。 我想获取httpclient的cookie并保存它。 所以下次我可以将cookie提供给httpclient,我可以再次访问bbs。 所以我的问题是如何从httpclient获取cookie。 以及如何保存cookie。 以及如何设置httpclient使用的cookie。 谢谢。

2 个答案:

答案 0 :(得分:0)

这样做:

Header[]     headers = null;
HttpResponse response = null;
HttpClient   httpclient = new DefaultHttpClient(params);                
HttpPost     post = new HttpPost(URI.create(this._strBaseUrl));




 response = httpclient.execute(post);

请求返回后,通过以下方式提取cookie:

headers = response.getHeaders("Set-Cookie");

然后您可以迭代cookie值(如有必要)。

答案 1 :(得分:0)

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
BasicCookieStore cookieStore = new BasicCookieStore();
context.setCookieStore(cookieStore);

HttpGet httpget = new HttpGet("https://host/stuff");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    List<Cookie> cookies = cookieStore.getCookies();
    if (cookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
        }
    }
    EntityUtils.consume(response.getEntity());
} finally {
    response.close();
}

请注意,您需要使用官方Apache HttpClient port to Android