java HttpClient

//获取返回请求中的sessionId
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("url");
method.getParams().setContentCharset("utf-8");
int statusCode = client.executeMethod(method);
System.out.println(".....................statusCode:"+statusCode);

String sessionId = "";
Header[] headers = method.getResponseHeaders();
for(Header temp:headers ){
    if("Set-Cookie".equals(temp.getName())){
        String[] cookies = temp.getValue().split(";");
        for(String cookie:cookies){
            if(cookie.indexOf("JSESSIONID")!=-1){
                sessionId = cookie.replaceAll("JSESSIONID=", "").replaceAll(" ", "");
            }
        }
        break;
    }
}

System.out.println("sessionId:"+sessionId);

//模拟浏览器,设置sessionId到Cookie
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("url");
method.getParams().setContentCharset("utf-8");
Header h = new Header();
h.setName("Cookie");
h.setValue("JSESSIONID=3E94E00349CA477A28F13F51EAB613FF");
method.setRequestHeader(h);
int statusCode = client.executeMethod(method);

你可能感兴趣的:(httpclient)