![](/img/trans.png)
[英]How to pass security cookies into a HttpClient Get request (Apache Commons)
[英]apache commons httpclient 4.23 form login problems different session cookies used in different requests
我有一個受保護的資源,需要我登錄。 我在下面的代碼塊中使用了commons客戶端。
HttpClient httpClient = new HttpClient();
httpClient.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
httpClient.getParams().setParameter("http.protocol.single-cookie-header", Boolean.TRUE);
PostMethod postMethod = new PostMethod("/admin/adminlogon.do");
postMethod.setRequestEntity(new StringRequestEntity("action=logon&adminUser=admin&adminPassword=password",
"application/x-www-form-urlencoded",
"UTF-8"));
postMethod.addParameter("action","logon");
postMethod.addParameter("adminUser","admin");
postMethod.addParameter("adminPassword","password");
httpClient.executeMethod(postMethod);
String response2 = postMethod.getResponseBodyAsString();
以上是我基本上登錄的地方。 即時獲得一個不錯的JSESSIONID cookie效果很好。
GetMethod get = new GetMethod("/admin/api.do?action=getSomeJson");
httpClient.executeMethod(get);
當我檢查第二個請求的服務器邏輯時,我注意到我們正在使用不同的JSESSIONID。 因此,get似乎無法登錄。給我的印象是httpClient管理cookie並將相同的cookie發送回去。 當我通常通過UI登錄到我的應用程序時,我在每個請求中看到的是同一個cookie,只是不在此測試代碼中。
String s = get.getResponseBodyAsString();
get.releaseConnection();
我是否需要對httpClient做一些事情以確保它在獲取請求時使用第一個發布請求中的相同cookie?
提前致謝。
您對HTTP客戶端Cookie行為的假設是正確的。 在您的情況下,您不能使用相同的httpClient實例。 要解決此問題,您只需要分配一次httpClient(在PostConstructor中):
httpClient = new DefaultHttpClient(); // or new HttpClient();
然后,您使用客戶端的相同實例執行呼叫。 客戶端將從響應中獲取一個cookie,並將其存儲在cookieStore中,並將其與下一個請求一起發送。
[在評論后添加]以下代碼對我有用:
httpClient = new DefaultHttpClient();
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Set the store
httpClient.setCookieStore(cookieStore);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.