问题描述
如何退出HttpClient会话?
How to exit from HttpClient session?
我使用以下代码使用Apache HttpClient登录到应用程序
I use the following code to login to the application using 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
方法的类.
如果我要使用具有不同用户名和密码的多个用户登录系统,怎么办?.
If I want to login to the system with multiple user with diffrent user name and password how to do this?.
例如,在同一会话中,我要注销一个用户并使用另一用户登录.
Like for example in the same session I want to logout one user and login using other user.
推荐答案
您可以使用一种解决方法–使用新的cookieStore向新用户发送请求.
You may use a workaround – to send a request to a new user with a new cookieStore.
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Set the store
httpClient.setCookieStore(cookieStore);
服务器将与您的新用户打开一个新会话.请注意,旧的会议不会关闭.我不建议使用这种方式.
Server will open a new session to your new user. Please note that the old session will NOT be closed.I do not recommend to use this way.
会话管理在服务器端执行–您不能在客户端执行此操作.我建议在测试结束时,您应调用服务器URL,这将使服务器端的会话无效.(通常,使用表单身份验证的应用程序具有注销功能,您只需要使用它即可)
The session management is performed on the server side – you can not do it on the client side.I recommend in the end of your test you should call to a server URL that will invalidate a session on the server side.(Generally applications that use Form authentication have a logout functionality and you just need to use it)
这篇关于退出HttpClient会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!