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