2013年10月4日 星期五

采用apache 的httpclient工具进行http请求(保持session会话)

http://www.heiqu.com/show-71029-1.html

采用apache 的httpclient工具进行http请求(保持session会话)

23小时前

  /**

  * 采用apache httpclient工具,依赖jar包 common-codec common-log和 common-httpclient 都是apache的jar包

  * cookice 原理,默认情况下,服务器会把session写在cookie里,所以禁用cookie会导致session丢失,若果吧session记录下来,

  * 会保持session,当发现session过期时候,更新session,就能保证继续访问

  * @author 于堃

  *

  */

  import java.io.IOException;

  import java.util.HashMap;

  import java.util.Map;

  import org.apache.commons.httpclient.Cookie;

  import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;

  import org.apache.commons.httpclient.HttpClient;

  import org.apache.commons.httpclient.HttpException;

  import org.apache.commons.httpclient.HttpStatus;

  import org.apache.commons.httpclient.methods.GetMethod;

  import org.apache.commons.httpclient.params.HttpMethodParams;

  public class HttpUtil {

  private static String DEFAULT_ENCODE="UTF-8";

  private HttpClient httpClient = new HttpClient();

  private Map<String,Cookie[]>history=new HashMap<String,Cookie[]>();

  private Map<String,Cookie>sessions=new HashMap<String,Cookie>();

  public String doGet(String url) throws HttpException, IOException

  {

  return doGet(url,DEFAULT_ENCODE);

  }

  public synchronized String doGet(String url,String encode)throws HttpException,IOException

  {

  String host=url.replaceFirst("\\w+://","");//正则表达式

  int offset=host.indexOf("/");

  if(offset!=-1)

  {

  host=host.substring(0,offset);

  }

  Cookie session=sessions.get(host);

  GetMethod doGET =new GetMethod(url);

  doGET.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,

  new DefaultHttpMethodRetryHandler());

  if(session!=null)//保持会话

  {

  httpClient.getState().addCookie(session);

  }

  int statusCode = httpClient.executeMethod(doGET);

  if (statusCode !=HttpStatus.SC_OK)

  {

  return null;

  }

  byte[] response = doGET.getResponseBody();

  String response_str=new String(response,encode);

  Cookie[] cookies =httpClient.getState().getCookies();

  for(Cookie cookie:cookies)

  {

  String name=cookie.getName();

  if(name.endsWith("SESSIONID"))

  {

  if(session==null||!session.getValue().equals(cookie.getValue()))

  {

  sessions.put(host, cookie); //会话过期,续期

  }

  }

  }

  doGET.releaseConnection();

  return response_str;

  }

  }



原文地址:http://user.qzone.qq.com/253620527/blog/1303655583