繁体   English   中英

如何从httpclient获取cookie?

[英]How can I get cookie from httpclient?

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

像这样做:

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值(如有必要)。

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端口连接Android

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM