2011-06-07 52 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