我正在使用 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的结构,或者我是否遗漏了一些东西。