2011-06-07 41 views
33

我正在使用HttpClient 4.1.1来测试我的服务器的REST API。如何在HttpClient 4.1中处理会话

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

我很可能在下一个请求中设置了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设置?

回答

64

正确的方法是准备一个CookieStore,您需要在HttpContext中设置,然后再调用每个HttpClient#execute()

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); 
// ... 
+14

如果会话过期会发生什么情况? – 2012-03-28 06:42:57