6
如何退出HttpClient會話?退出HttpClient會話
我使用下面的代碼使用Apache的HttpClient
public HttpClient loginToHexgen(String username, String password) {
HttpClient client = new DefaultHttpClient();
// send post url to login to hexgen
HttpPost post = new HttpPost("http://localhost:8080/j_spring_security_check");
try {
// set the user name and password
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("j_username", username));
nameValuePairs.add(new BasicNameValuePair("j_password", password));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
post.abort();
}
} catch (IOException e) {
e.printStackTrace();
}
return client;
}
像下面登錄到應用程序:
HttpClient client = new DefaultHttpClient();
client= httpRequest.loginToHexgen("mayank", "hexgen");
這裏httpRequest
是其中使用loginToHexgen
方法的類。
如果我想用多個用戶以不同的用戶名和密碼登錄系統,該怎麼做?
例如在同一個會話中,我想註銷一個用戶並使用其他用戶登錄。
+1對於答案,我試圖用不同的密碼發送不同的用戶,但令我驚訝的是它沒有產生任何問題,當我縮進時工作。感謝您的努力。 – 2013-05-13 07:45:48
在'loginToHexgen'函數中有以下代碼的問題:'HttpClient client = new DefaultHttpClient();'。 它等於爲新用戶創建cookieStore。 注意事項:1.如果您想要代表經過身份驗證的用戶訪問URL,則需要使用相同的HttpClient實例(否則請求將沒有合唱)。 2.你可以檢查你的服務器,你會看到每個登錄一個新的會話被創建。 – Michael 2013-05-13 10:50:21