httpclient cookie保持會話


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);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM