【问题标题】:How can I get cookie from httpclient?如何从 httpclient 获取 cookie?
【发布时间】:2014-06-07 21:53:11
【问题描述】:

我用httppost登录了一个bbs。 httpclient可以自动保存cookie等信息。 我想为 httpclient 获取 cookie 并保存它。 所以下次我可以把cookie交给httpclient,我就可以再次访问bbs了。 所以我的问题是如何从 httpclient 获取 cookie。 以及如何保存 cookie。 以及如何设置 httpclient 使用的 cookie。 谢谢。

【问题讨论】:

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


    【解决方案1】:
    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

    【讨论】:

    • 我想你忘了用上下文做点什么?
    【解决方案2】:

    这样做:

    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 值(如果需要)。

    【讨论】:

      猜你喜欢
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多