2012-09-19 64 views
4

我想弄清楚如何使用HttpComponents設置和檢索cookie,但我無法找到可靠的文檔,特別是當涉及到在請求中設置Cookie時。我似乎工作,但同時我不能確認我設置的cookie被正確發送。使用HttpComponents設置和檢索Cookie

我注意到我在請求上設置的cookie在調用client.execute()後也在CookieStore中,但我不確定這是否因爲我在調用client.execute之前將它添加到了CookieStore中( )(也許它保留在CookieStore中,而沒有實際發送請求?)。有沒有一種確認cookie被髮送的好方法?

HttpGet get = new HttpGet("http://example.com/"); 
DefaultHttpClient client = new DefaultHttpClient(); 

// set the cookies 
CookieStore cookieStore = new BasicCookieStore(); 
BasicClientCookie cookie = new BasicClientCookie("foo", "bar"); 
cookie.setDomain("example.com"); 
cookie.setPath("/something/"); 
cookieStore.addCookie(cookie);  
client.setCookieStore(cookieStore); 

// get the cookies 
HttpResponse response = client.execute(get); 
List<Cookie> cookies = client.getCookieStore().getCookies(); 
+0

使用Wireshark捕獲包跟蹤,或者記錄請求如果您擁有服務器代碼的控制權,則可以從服務器端獲取內容。 –

回答

2

剛發現的follwoing例子演示了在登錄例如使用cookies:HttpComponents Example with Cookies

也許你可以在什麼樣的服務器發送的cookie的內容進行響應的方式改變這一點,所以你可以評估cookie是否真的被髮送到服務器。 (你發送cookie到「foo」,「bar」或一些隨機值,服務器會用「bar」,「foo」或類似的東西迴應)

+0

該示例確實展示瞭如何檢索cookie,但我沒有看到它如何設置它們。 – acvcu

+0

猜測這是在entity.consumeContent()中完成的; – jethroo