HttpClient是一个客户端的HTTP通信实现库,目标是发送和接受HTTP请求。HTTPClient维护cookies,session的保持在客户端就是cookie的体现。HttpClinet的session的保持有两种方式,一种是将HttpClient实例保存于web应用的session中,再次请求时取出,因为httpclient会维持cookies。另一种是再次请求时,将上次请求获取的cookies带入请求中,此种方式无需将httpclient保存于session中。
NameValuePair[] param = { new NameValuePair("username",userId),
new NameValuePair("password",password) } ;
//第一种方式 httpclient保存于session,每次请求均为同一httpclient,httpclient维持cookies
//HttpClient client =(HttpClient) request.getSession().getAttribute("HTTPCLIENT");
//第二种方式 每次请求带入之前请求获取的cookies。
HttpClient client=new HttpClient();
client.getState().addCookies(cookies);
PostMethod post=new PostMethod(url);
client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
post.setRequestBody(param);
client.executeMethod(post);
Cookie[] cookies=client.getState().getCookies();
post.releaseConnection();