如何在HttpClient 4.1中处理会话

时间:2011-06-07 23:03:13

标签: java session cookies httpclient

我正在使用HttpClient 4.1.1来测试我的服务器的REST API。

我可以设法登录似乎工作正常,但当我尝试做任何其他事情时,我失败了。

我很可能在下一次请求中设置cookie时遇到问题。

这是我目前的代码:

HttpGet httpGet = new HttpGet(<my server login URL>);
httpResponse = httpClient.execute(httpGet)
sessionID = httpResponse.getFirstHeader("Set-Cookie").getValue();
httpGet.addHeader("Cookie", sessionID);
httpClient.execute(httpGet);

有没有更好的方法来管理HttpClient包中的会话/ cookie设置?

1 个答案:

答案 0 :(得分:68)

正确的方法是准备CookieStore,您需要在HttpContext中设置HttpClient#execute(),而{{3}}则会在每次{{3}}来电时传递。

HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
// ...

HttpResponse response1 = httpClient.execute(method1, httpContext);
// ...

HttpResponse response2 = httpClient.execute(method2, httpContext);
// ...