如何退出 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");
here httpRequest
是所在的类loginToHexgen
方法被使用。
如果我想使用多个用户使用不同的用户名和密码登录系统,该怎么做?
例如,在同一会话中,我想注销一个用户并使用其他用户登录。
您可以使用一种解决方法 – 使用新的 cookieStore 向新用户发送请求。
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Set the store
httpClient.setCookieStore(cookieStore);
服务器将为您的新用户打开一个新会话。请注意,旧会话不会关闭。
我不建议使用这种方式。
会话管理是在服务器端执行的 - 您不能在客户端执行。
我建议在测试结束时您应该调用一个服务器 URL,该 URL 将使服务器端的会话无效。
(一般使用Form认证的应用都有注销功能,您只需使用即可)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)