1. 程式人生 > >httpclient妙用二 httpclient保持會話登入

httpclient妙用二 httpclient保持會話登入

httpclient保持會話登入

1.原理

    httpclient會話保持,原理是維持session會話,而session的保持是通過cookie來維持的。

    本次要講的是,得到使用者cookie後,免登入,用HttpClient 保持原來session訪問原本一定要登入才能做的事。

2.maven工程中引入對httpclient的依賴

Xml程式碼  收藏程式碼
  1. <properties>  
  2.     <httpclient.version>4.3.2</httpclient.version>  
  3. <properties>
      
  4. <dependencyManagement>  
  5.     <dependency>  
  6.         <groupId>commons-logging</groupId>  
  7.         <artifactId>commons-logging</artifactId>  
  8.         <version>1.1.1</version>  
  9.     </dependency>  
  10.     <dependencies>  
  11.             <!-- httpclient -->
      
  12.     <dependency>  
  13.         <groupId>org.apache.httpcomponents</groupId>  
  14.         <artifactId>httpclient</artifactId>  
  15.         <version>${httpclient.version}</version>  
  16.         <exclusions>  
  17.             <exclusion>  
  18.                 <groupId
    >commons-logging</groupId>  
  19.                 <artifactId>commons-logging</artifactId>  
  20.             </exclusion>  
  21.         </exclusions>  
  22.     </dependency>  
  23.     <dependency>  
  24.         <groupId>org.apache.httpcomponents</groupId>  
  25.         <artifactId>fluent-hc</artifactId>  
  26.         <version>${httpclient.version}</version>  
  27.         <exclusions>  
  28.             <exclusion>  
  29.                 <groupId>commons-logging</groupId>  
  30.                 <artifactId>commons-logging</artifactId>  
  31.             </exclusion>  
  32.         </exclusions>  
  33.     </dependency>  
  34.     <dependency>  
  35.         <groupId>org.apache.httpcomponents</groupId>  
  36.         <artifactId>http-core</artifactId>  
  37.         <version>${httpclient.version}</version>  
  38.         <exclusions>  
  39.             <exclusion>  
  40.                 <groupId>commons-logging</groupId>  
  41.                 <artifactId>commons-logging</artifactId>  
  42.             </exclusion>  
  43.         </exclusions>  
  44.     </dependency>  
  45. </dependencies>  
  46. lt;/dependencyManagement>  

3.第一種情況:每次登入後才進行後續操作

   這種情況不用去處理cookie,httpclient4.x會自動處理cookie,只要使用同一httpclient,且沒有手動連線放掉httpclient

Java程式碼  收藏程式碼
  1. import java.util.ArrayList;  
  2. import java.util.HashMap;  
  3. import java.util.List;  
  4. import java.util.Map;  
  5. import org.apache.http.NameValuePair;  
  6. import org.apache.http.client.config.RequestConfig;  
  7. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  8. import org.apache.http.client.methods.CloseableHttpResponse;  
  9. import org.apache.http.client.methods.HttpPost;  
  10. import org.apache.http.impl.client.CloseableHttpClient;  
  11. import org.apache.http.impl.client.HttpClientBuilder;  
  12. import org.apache.http.message.BasicNameValuePair;  
  13. import org.apache.http.util.EntityUtils;  
  14. public class KeepSessionWithOneHttpclient {  
  15.     /** 
  16.      * 如果用的是同一個HttpClient且沒去手動連線放掉client.getConnectionManager().shutdown(); 
  17.      * 都不用去設定cookie的ClientPNames.COOKIE_POLICY。httpclient都是會保留cookie的 
  18.      * @param loginUrl 
  19.      * @param loginNameValuePair 
  20.      * @param urlAndNamePairList 
  21.      * @return 
  22.      */  
  23.     public static Map<String,String> doPostWithOneHttpclient(String loginUrl,List<NameValuePair> loginNameValuePair,  
  24.             Map<String,List<NameValuePair>> urlAndNamePairList) {  
  25.         //返回每個URL對應的響應資訊  
  26.         Map<String,String> map = new HashMap<String,String>();  
  27.         String retStr = "";//每次響應資訊  
  28.         int statusCode = 0 ;//每次響應程式碼  
  29.         // 建立HttpClientBuilder  
  30.         HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
  31.         // HttpClient  
  32.         CloseableHttpClient closeableHttpClient = null;  
  33.         closeableHttpClient = httpClientBuilder.build();  
  34.         HttpPost httpPost = new HttpPost(loginUrl);  
  35.         // 設定請求和傳輸超時時間  
  36.         RequestConfig requestConfig = RequestConfig.custom()  
  37.                 .setSocketTimeout(30000)  
  38.                 .setConnectTimeout(30000).build();  
  39.         httpPost.setConfig(requestConfig);  
  40.         UrlEncodedFormEntity entity = null;  
  41.         try {  
  42.             if(null!=loginNameValuePair){  
  43.                 entity = new UrlEncodedFormEntity(loginNameValuePair, "UTF-8");  
  44.                 httpPost.setEntity(entity);  
  45.             }  
  46.             //登入  
  47.             CloseableHttpResponse loginResponse = closeableHttpClient.execute(httpPost);  
  48.             statusCode = loginResponse.getStatusLine().getStatusCode();  
  49.             retStr = EntityUtils.toString(loginResponse.getEntity(), "UTF-8");  
  50.             map.put(loginUrl, retStr);  
  51.             //登入後其他操作  
  52.             for(Map.Entry<String,List<NameValuePair>> entry : urlAndNamePairList.entrySet()){  
  53.                 String url = entry.getKey();  
  54.                 List<NameValuePair> params = urlAndNamePairList.get(url);  
  55.                 httpPost = new HttpPost(url);  
  56.                 if(null!=params){  
  57.                     entity = new UrlEncodedFormEntity(params, "UTF-8");  
  58.                     httpPost.setEntity(entity);  
  59.                 }  
  60.                 CloseableHttpResponse operationResponse = closeableHttpClient.execute(httpPost);  
  61.                 statusCode = operationResponse.getStatusLine().getStatusCode();  
  62.                 retStr = EntityUtils.toString(operationResponse.getEntity(), "UTF-8");  
  63.                 map.put(url, retStr);  
  64.                 if(statusCode == 302){  
  65.                     String redirectUrl = operationResponse.getLastHeader("Location").getValue();  
  66.                     httpPost = new HttpPost(redirectUrl);  
  67.                     CloseableHttpResponse redirectResponse = closeableHttpClient.execute(httpPost);  
  68.                     statusCode = redirectResponse.getStatusLine().getStatusCode();  
  69.                     retStr = EntityUtils.toString(redirectResponse.getEntity(), "UTF-8");  
  70.                     map.put(redirectUrl, retStr);  
  71.                 }  
  72.             }  
  73.             // 釋放資源  
  74.             closeableHttpClient.close();  
  75.         } catch (Exception e) {  
  76.             e.printStackTrace();  
  77.         }  
  78.         return map;  
  79.     }  
  80.     public static void main(String[] args) {  
  81.         //登入的地址以及登入操作引數  
  82.         String loginUrl = "http://public_ip/xxx/sso_login";  
  83.         //登入的相關引數以及登入後操作引數  
  84.         List<NameValuePair> loginParams = new ArrayList<NameValuePair>();  
  85.         loginParams.add(new BasicNameValuePair("sso_callback_uri","/xxx/forward?locale=zh_CN"));  
  86.         loginParams.add(new BasicNameValuePair("appName""xxx"));  
  87.         loginParams.add(new BasicNameValuePair("username""xxx"));  
  88.         loginParams.add(new BasicNameValuePair("password""xxx"));  
  89.         //登入後操作地址以及登入後操作引數  
  90.         String queryUrl = "http://public_ip/xxx/system/getRegionList.do";  
  91.         List<NameValuePair> queryParams = new ArrayList<NameValuePair>();  
  92.         queryParams.add(new BasicNameValuePair("regionNo""xxx"));  
  93.         queryParams.add(new BasicNameValuePair("pageNo""xxx"));  
  94.         queryParams.add(new BasicNameValuePair("pageSize""xxx"));  
  95.         Map<String,List<NameValuePair>> map = new HashMap<String,List<NameValuePair>>();  
  96.         map.put(queryUrl, queryParams);  
  97.         Map<String,String> returnMap = doPostWithOneHttpclient(loginUrl, loginParams, map);  
  98.         System.out.println(returnMap.toString());  
  99.     }  
  100. }  

 4.第二種情況:登入一次,後續使用之前登入時的cookie

    登入後,將cookie儲存起來,待有其他操作時,不用再次登入,首先設定cookie,然後呼叫操作

Java程式碼  收藏程式碼
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3. import org.apache.http.HttpEntity;  
  4. import org.apache.http.HttpResponse;  
  5. import org.apache.http.NameValuePair;  
  6. import org.apache.http.client.CookieStore;  
  7. import org.apache.http.client.config.RequestConfig;  
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  9. import org.apache.http.client.methods.CloseableHttpResponse;  
  10. import org.apache.http.client.methods.HttpPost;  
  11. import org.apache.http.impl.client.BasicCookieStore;  
  12. import org.apache.http.impl.client.CloseableHttpClient;  
  13. import org.apache.http.impl.client.HttpClientBuilder;  
  14. import org.apache.http.impl.cookie.BasicClientCookie;  
  15. import org.apache.http.message.BasicNameValuePair;  
  16. import org.apache.http.util.EntityUtils;  
  17. public class LoginWithHttpclient {  
  18.     static CookieStore cookieStore = null;  
  19.     /** 
  20.      * 組裝登入引數 
  21.      * @return 
  22.      */  
  23.     public static List<NameValuePair> getLoginNameValuePairList() {  
  24.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  25.         params.add(new BasicNameValuePair("sso_callback_uri","/xxx/forward?locale=zh_CN"));  
  26.         params.add(new BasicNameValuePair("appName""xxx"));  
  27.         params.add(new BasicNameValuePair("username""xxx"));  
  28.         params.add(new