如何在apache httpclient中获取客户端的会话ID

时间:2012-09-17 23:34:10

标签: java web-services httpclient session-variables apache-httpclient-4.x

我正在尝试使用username和pwd登录到webservice。 然后我必须在随后的调用中使用sessionid。我正在使用apache HttpClient(旧版本)2.0.2。

以下是我的客户端代码进行身份验证。我的问题是,如何在我进行身份验证后获取会话ID以及如何在后续调用中使用相同的会话ID。

import java.io.IOException;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
public class TestHttpClient {

    public static void main(String args[]) {
        try {
            HttpClient client = new HttpClient();
            GetMethod get = new HttpGet("www.google.com");

            org.apache.commons.httpclient.UsernamePasswordCredentials upc =
                    new org.apache.commons.httpclient.UsernamePasswordCredentials("user", "pwd");

            client.getState().setCredentials(null, null, upc);

            get.setDoAuthentication(true);

            client.setConnectionTimeout(60000);

            client.executeMethod(get);

            System.out.println(get.getResponseBodyAsString());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

}

感谢您帮助新手进行网络开发。

1 个答案:

答案 0 :(得分:1)

以下是获取会话ID的方法:

.......

client.executeMethod(get); 

Header[] headers=get.getResponseHeader("jsessionid");

if(headers!=null && headers.length>0){

 String sessionId=headers[0].getValue();

}

我确信在没有您阅读会话ID的情况下,会有更好的方法来处理经过身份验证的会话。