我正在使用HttpComponents 4.5.2,我试图存储cookies,因为我需要将它们用于登录和其他请求。在应用程序仍在运行时,代码运行良好,但这里的问题是,当我重新启动它时,本应存储在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文档,关于cookies的第3.5节说:
HttpClient可以使用实现CookieStore接口的持久性cookie存储的任何物理表示形式。名为CookieStore的默认BasicCookieStore实现是一个由java.util.ArrayList支持的简单实现。当容器对象被垃圾收集时,存储在BasicClientCookie对象中的Cookies就会丢失。如果需要,用户可以提供更复杂的实现。
所以,我想知道是由用户来实现某种能够有效存储cookie的结构,还是我遗漏了什么。
发布于 2016-10-16 18:07:26
是的,使用由BasicCookieStore支持的ArrayList意味着当您的jvm存在时,那里的数据就会像内存中的任何ArrayList一样丢失。
BasicCookieStore类还实现了Serializable,因此您可以使用它将其持久化到磁盘,并在文件存在的情况下在应用程序启动时恢复。
您可以从验证流TestBasicCookieStore#testSerialization的测试中借用一些代码。
https://stackoverflow.com/questions/40073468
复制相似问题