回到顶部


COOKIE保持回话

httpclient4.x自带维护回话的功能,只要使用同一个httpclient且未关闭连接,就可以使用相同的回话来访问其他要求登陆验证的服务。
如果需要使用HttpClient池,并且想要做到一次登陆的会话供多个httpClient连接使用,就需要自己保存回话信息。
客户端的回话信息是保存在cookie中的(JESSIONID),所以只需要将登陆成功返回的cookie复制到各个HttpClient使用即可。
使用Cookie的方法有两种,可以自己使用CookieStore来保存,也可以通过HttpClientContext上下文来维持

使用cookie的两种方法

*) 使用CookieStore来保存
*) 通过HttpClientContext上下文来维持

使用cookie测试登陆

public void testLogin(){
//间接创建HttpClient
 HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
 ColseableHttpClient client = httpClientBuilder.build();
//直接创建client
 CloseableHttpClient client = HttpClients.createDefault();
//-------------------------------------------------------------------------------- 
 HttpPost httpPost = new HttpPost(loginUrl);
 Map parameterMap = new HashMap();
 paramterMap.put("username","admin");
 paramterMap.put("password","admin123");
-------------------------------------------------------------------------------- 
 UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(paramterMap),"utf-8");
 httpPost.setEntity(postEntity);
 try{
  //--执行post请求
  HttpResponse httpResponse = client.execute(httpPost);
  String location = httpResponse.getFirstHeader("Location").getValue();
  printResponse(httpResponse);
  //--执行get请求
  HttpGet httpGet = new HttpGet(testUrl);
  HttpResponse response1 = client.execute(httpGet);
 printResponse(httpResponse);
-------------------------------------------------------------------------------- 
 //cookie Store 
 setCookieStore(httpResponse);
 //context  注意顺序
 setContext();
 }catch(Exception e){
  e.printStackTrace();
 }
}
-------------------------------------------------------------------------------- 
public static List<NameValuePair> getParam(Map parameterMap) {
    List<NameValuePair> param = new ArrayList<NameValuePair>();
    Iterator it = parameterMap.entrySet().iterator();
    while (it.hasNext()) {
      Entry parmEntry = (Entry) it.next();
      param.add(new BasicNameValuePair((String) parmEntry.getKey(),
          (String) parmEntry.getValue()));
    }
    return param;
  }
-------------------------------------------------------------------------
public static void printResponse(HttpResponse httpResponse)
      throws ParseException, IOException {
    // 获取响应消息实体
    HttpEntity entity = httpResponse.getEntity();
    // 响应状态
    System.out.println("status:" + httpResponse.getStatusLine());
    System.out.println("headers:");
    HeaderIterator iterator = httpResponse.headerIterator();
    while (iterator.hasNext()) {
      System.out.println("\t" + iterator.next());
    }
    // 判断响应实体是否为空
    if (entity != null) {
      String responseString = EntityUtils.toString(entity);
      System.out.println("response length:" + responseString.length());
      System.out.println("response content:"
          + responseString.replace("\r\n", ""));
    }
  }

通过CookieStore保持上下文的回话

static CookieStore cookieStore = null;

public void testCookieStore() throws Exception{
 //使用cookieStore方式
 cookieStore= setCookieStore();
 CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
 HttpGet httpGet = new HttpGet(testUrl);
 //执行get请求
 try{
   HttpResponse response = client.execute(httpGet);
   printResponse(response);
 }catch(Exception e){
   e.printStackTrace();  
 }
}
 
public static void setCookieStore(HttpResponse response){
  cookieStore = new BasicCookieStore();
  //JSSIONID
  String setCookie - httpResponse.getFirestHeader("Set-Cookie").getValue();
  String JESSIONID = setCookie.substring("JESSIONID=".length(),setCookie.indexOf(";"));
  //新建一个COOKIE
  BasicClientCookie cookie = new BasicClientCookie("JESSIONID",JESSIONID);
  cookie.setVersion(0);
  cookie.setDomain("127.0.0.1");
  cookie.setPath("/path");
  // cookie.setAttribute(ClientCookie.VERSION_ATTR, "0");
  // cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "127.0.0.1");
  // cookie.setAttribute(ClientCookie.PORT_ATTR, "8080");
  // cookie.setAttribute(ClientCookie.PATH_ATTR, "/CwlProWeb");
  cookieStore.addCookie(cookie);
}

使用context上下文保持回话

static HttpClientContext context = null;
public void testContext() throws Exception(
 //使用context方式
 CloseableHttpClient client = HttpClients.createDefault():
 HttpGet httpGet = new HttpGet(testUrl);
 try{
 //执行get请求
  HttpResponse httpResponse = client.execute(httpGet,context);
  printResponse(httpResponse);
 }catch(Exception e){
   e.printStackTrace();
 }finally{
   //关闭流并释放资源
   client.close();
 }
)

public static void setContext() {
    context = HttpClientContext.create();
    Registry<CookieSpecProvider> registry = RegistryBuilder
        .<CookieSpecProvider> create()
        .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
        .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()).build();
    context.setCookieSpecRegistry(registry);
    context.setCookieStore(cookieStore);
}
posted on 2018-04-14 06:11  ssgao  阅读(5254)  评论(0编辑  收藏  举报