【问题标题】:Apache HttpComponents CookieStore Not Storing CookiesApache HttpComponents CookieStore 不存储 Cookie
【发布时间】:2016-10-16 17:51:46
【问题描述】:

我正在使用 HttpComponents 4.5.2 并且我正在尝试存储 cookie,因为我需要将它们用于登录和其他请求。该代码在应用程序仍在运行时工作正常,但这里的问题是当我重新启动它时,应该存储在 CookieStore 中的 cookie 不存在。这是我写的:

public static void main( String[] args ) throws InterruptedException
{
    RequestConfig globalConfig = RequestConfig.custom()
            .setCookieSpec(CookieSpecs.STANDARD).build();
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
            .setDefaultRequestConfig(globalConfig)
            .setDefaultCookieStore(cookieStore)
            .build();
    httpclient.start();
    login(httpclient, context);
}

public static void login(CloseableHttpAsyncClient httpClient, HttpClientContext context) throws InterruptedException
{
    JSONObject json = new JSONObject("{ email : blahblahblah1, password : blahblahblah2 }");
    StringEntity requestEntity = new StringEntity(
            json.toString(),
            ContentType.APPLICATION_JSON);

    HttpPost postMethod = new HttpPost("http://localhost:8080/login");
    postMethod.setEntity(requestEntity);

    final CountDownLatch latch = new CountDownLatch(1);
    httpClient.execute(postMethod, context, new FutureCallback<HttpResponse>() {

        public void completed(final HttpResponse response) {
            latch.countDown();
            System.out.println(postMethod.getRequestLine() + "->" + response.getStatusLine());
            //System.out.println(context.getCookieStore().getCookies().size());
        }

        public void failed(final Exception ex) {
            latch.countDown();
            System.out.println(postMethod.getRequestLine() + "->" + ex);
        }

        public void cancelled() {
            latch.countDown();
            System.out.println(postMethod.getRequestLine() + " cancelled");
        }

    });
    latch.await();
}

我已经阅读了 HttpComponents 文档和关于 cookie 的第 3.5 节说:

HttpClient 可以与实现 CookieStore 接口的持久 cookie 存储的任何物理表示一起使用。称为 BasicCookieStore 的默认 CookieStore 实现是一个由 java.util.ArrayList 支持的简单实现。当容器对象被垃圾回收时,存储在 BasicClientCookie 对象中的 Cookie 会丢失。如有必要,用户可以提供更复杂的实现

所以我想知道是否由用户来实现某种可以有效存储 cookie 的结构,或者我是否遗漏了什么。

【问题讨论】:

    标签: apache-httpclient-4.x apache-httpcomponents apache-httpasyncclient


    【解决方案1】:

    是的,使用由ArrayList 支持的BasicCookieStore 意味着当你的jvm 存在时,那里的数据就像内存中的任何ArrayList 一样丢失。

    BasicCookieStore 类还实现了Serializable,因此您可以使用它将其持久化到磁盘并在您的应用启动时恢复(如果该文件存在)。

    您可以从验证流程TestBasicCookieStore#testSerialization 的测试中借用一些代码。

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 2013-02-07
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多