Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit from HttpClient session

How to exit from HttpClient session?

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;
    }

like the following :

HttpClient client = new DefaultHttpClient();
client= httpRequest.loginToHexgen("mayank", "hexgen");

here httpRequest is the class where the loginToHexgen method is used.

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.

like image 838
Java Questions Avatar asked May 13 '13 05:05

Java Questions


Video Answer


1 Answers

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.

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)

like image 185
Michael Avatar answered Oct 16 '22 23:10

Michael