httpclient妙用二 httpclient保持會話登入
阿新 • • 發佈:2019-02-01
httpclient保持會話登入
1.原理
httpclient會話保持,原理是維持session會話,而session的保持是通過cookie來維持的。
本次要講的是,得到使用者cookie後,免登入,用HttpClient 保持原來session訪問原本一定要登入才能做的事。
2.maven工程中引入對httpclient的依賴
Xml程式碼- <properties>
- <httpclient.version>4.3.2</httpclient.version>
-
<properties>
- <dependencyManagement>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.1.1</version>
- </dependency>
- <dependencies>
-
<!-- httpclient -->
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- <version>${httpclient.version}</version>
- <exclusions>
- <exclusion>
-
<groupId
- <artifactId>commons-logging</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>fluent-hc</artifactId>
- <version>${httpclient.version}</version>
- <exclusions>
- <exclusion>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>http-core</artifactId>
- <version>${httpclient.version}</version>
- <exclusions>
- <exclusion>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- </dependencies>
- lt;/dependencyManagement>
3.第一種情況:每次登入後才進行後續操作
這種情況不用去處理cookie,httpclient4.x會自動處理cookie,只要使用同一httpclient,且沒有手動連線放掉httpclient
Java程式碼- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.config.RequestConfig;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClientBuilder;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- public class KeepSessionWithOneHttpclient {
- /**
- * 如果用的是同一個HttpClient且沒去手動連線放掉client.getConnectionManager().shutdown();
- * 都不用去設定cookie的ClientPNames.COOKIE_POLICY。httpclient都是會保留cookie的
- * @param loginUrl
- * @param loginNameValuePair
- * @param urlAndNamePairList
- * @return
- */
- public static Map<String,String> doPostWithOneHttpclient(String loginUrl,List<NameValuePair> loginNameValuePair,
- Map<String,List<NameValuePair>> urlAndNamePairList) {
- //返回每個URL對應的響應資訊
- Map<String,String> map = new HashMap<String,String>();
- String retStr = "";//每次響應資訊
- int statusCode = 0 ;//每次響應程式碼
- // 建立HttpClientBuilder
- HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
- // HttpClient
- CloseableHttpClient closeableHttpClient = null;
- closeableHttpClient = httpClientBuilder.build();
- HttpPost httpPost = new HttpPost(loginUrl);
- // 設定請求和傳輸超時時間
- RequestConfig requestConfig = RequestConfig.custom()
- .setSocketTimeout(30000)
- .setConnectTimeout(30000).build();
- httpPost.setConfig(requestConfig);
- UrlEncodedFormEntity entity = null;
- try {
- if(null!=loginNameValuePair){
- entity = new UrlEncodedFormEntity(loginNameValuePair, "UTF-8");
- httpPost.setEntity(entity);
- }
- //登入
- CloseableHttpResponse loginResponse = closeableHttpClient.execute(httpPost);
- statusCode = loginResponse.getStatusLine().getStatusCode();
- retStr = EntityUtils.toString(loginResponse.getEntity(), "UTF-8");
- map.put(loginUrl, retStr);
- //登入後其他操作
- for(Map.Entry<String,List<NameValuePair>> entry : urlAndNamePairList.entrySet()){
- String url = entry.getKey();
- List<NameValuePair> params = urlAndNamePairList.get(url);
- httpPost = new HttpPost(url);
- if(null!=params){
- entity = new UrlEncodedFormEntity(params, "UTF-8");
- httpPost.setEntity(entity);
- }
- CloseableHttpResponse operationResponse = closeableHttpClient.execute(httpPost);
- statusCode = operationResponse.getStatusLine().getStatusCode();
- retStr = EntityUtils.toString(operationResponse.getEntity(), "UTF-8");
- map.put(url, retStr);
- if(statusCode == 302){
- String redirectUrl = operationResponse.getLastHeader("Location").getValue();
- httpPost = new HttpPost(redirectUrl);
- CloseableHttpResponse redirectResponse = closeableHttpClient.execute(httpPost);
- statusCode = redirectResponse.getStatusLine().getStatusCode();
- retStr = EntityUtils.toString(redirectResponse.getEntity(), "UTF-8");
- map.put(redirectUrl, retStr);
- }
- }
- // 釋放資源
- closeableHttpClient.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return map;
- }
- public static void main(String[] args) {
- //登入的地址以及登入操作引數
- String loginUrl = "http://public_ip/xxx/sso_login";
- //登入的相關引數以及登入後操作引數
- List<NameValuePair> loginParams = new ArrayList<NameValuePair>();
- loginParams.add(new BasicNameValuePair("sso_callback_uri","/xxx/forward?locale=zh_CN"));
- loginParams.add(new BasicNameValuePair("appName", "xxx"));
- loginParams.add(new BasicNameValuePair("username", "xxx"));
- loginParams.add(new BasicNameValuePair("password", "xxx"));
- //登入後操作地址以及登入後操作引數
- String queryUrl = "http://public_ip/xxx/system/getRegionList.do";
- List<NameValuePair> queryParams = new ArrayList<NameValuePair>();
- queryParams.add(new BasicNameValuePair("regionNo", "xxx"));
- queryParams.add(new BasicNameValuePair("pageNo", "xxx"));
- queryParams.add(new BasicNameValuePair("pageSize", "xxx"));
- Map<String,List<NameValuePair>> map = new HashMap<String,List<NameValuePair>>();
- map.put(queryUrl, queryParams);
- Map<String,String> returnMap = doPostWithOneHttpclient(loginUrl, loginParams, map);
- System.out.println(returnMap.toString());
- }
- }
4.第二種情況:登入一次,後續使用之前登入時的cookie
登入後,將cookie儲存起來,待有其他操作時,不用再次登入,首先設定cookie,然後呼叫操作
Java程式碼- import java.util.ArrayList;
- import java.util.List;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.CookieStore;
- import org.apache.http.client.config.RequestConfig;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.BasicCookieStore;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClientBuilder;
- import org.apache.http.impl.cookie.BasicClientCookie;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- public class LoginWithHttpclient {
- static CookieStore cookieStore = null;
- /**
- * 組裝登入引數
- * @return
- */
- public static List<NameValuePair> getLoginNameValuePairList() {
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("sso_callback_uri","/xxx/forward?locale=zh_CN"));
- params.add(new BasicNameValuePair("appName", "xxx"));
- params.add(new BasicNameValuePair("username", "xxx"));
- params.add(new