退出HttpClient会话

Jav*_*ons 7 java apache-httpclient-4.x

如何退出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;
    }
Run Code Online (Sandbox Code Playgroud)

如下:

HttpClient client = new DefaultHttpClient();
client= httpRequest.loginToHexgen("mayank", "hexgen");
Run Code Online (Sandbox Code Playgroud)

这是使用httpRequestloginToHexgen方法的类.

如果我想用多个用户登录系统,用户名和密码不同怎么办?

例如,在同一会话中,我想注销一个用户并使用其他用户登录.

Mic*_*ael 5

您可以使用一种解决方法–使用新的cookieStore向新用户发送请求。

// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Set the store
httpClient.setCookieStore(cookieStore);
Run Code Online (Sandbox Code Playgroud)

服务器将向您的新用户打开一个新会话。请注意,旧的会议不会关闭。我不建议使用这种方式。

会话管理在服务器端执行–您不能在客户端执行此操作。我建议在测试结束时,应调用服务器URL,这将使服务器端的会话无效。(通常,使用表单身份验证的应用程序具有注销功能,您只需要使用它即可)