【问题标题】:How do I get the cookies from Apache HttpClient 4.x?如何从 Apache HttpClient 4.x 获取 cookie?
【发布时间】:2014-03-05 17:51:09
【问题描述】:

如何从 HttpClient 类型的现有对象中获取 cookie? 我正在使用 HttpClient 版本 4.3.3,它没有方法 httpClient.getCookieStore() 了。

【问题讨论】:

    标签: httpclient apache-httpclient-4.x apache-commons-httpclient


    【解决方案1】:
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpClientContext context = HttpClientContext.create();
    CloseableHttpResponse response = httpclient.execute(new HttpGet("/"), context);
    try {
        CookieStore cookieStore = context.getCookieStore();
        List<Cookie> cookies = cookieStore.getCookies();
    } finally {
        response.close();
    }
    

    【讨论】:

    • 我希望无需像版本 3 那样创建自己的 HttpClientContext 就可以获取 HttpClient 的 CookieStore。
    • @eztam:为什么? HttpClient 总是需要一个执行上下文,因此如果没有明确给出,则会在后台创建一个。
    • @ok2c 因为它在某些完全正常的情况下会导致@#$@#$@#$ 背部疼痛
    • @YannickMenager 究竟是什么情况下所说的背部疼痛?执行上下文?
    【解决方案2】:

    版本 4.5.2 您可以使用此代码:

    List<Cookie> cookies = ((CookieStore)localContext.getAttribute(HttpClientContext.COOKIE_STORE)).getCookies();
    

    【讨论】:

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