日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

JAVA——保持cookie登录状态的HttpClient封装工具类

發(fā)布時(shí)間:2024/10/5 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JAVA——保持cookie登录状态的HttpClient封装工具类 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

在日常開發(fā)中,我們經(jīng)常需要通過http協(xié)議去調(diào)用網(wǎng)絡(luò)內(nèi)容,雖然java自身提供了net相關(guān)工具包,但是其靈活性和功能總是不如人意,于是有人專門搞出一個(gè)httpclient類庫(kù),來方便進(jìn)行Http操作。簡(jiǎn)單的對(duì)httpcient的簡(jiǎn)單操作封裝成一個(gè)工具類,統(tǒng)一放在項(xiàng)目的工具包中,在使用的時(shí)候直接從工具包中調(diào)用,不需要寫冗余代碼。

Maven

<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-collections4</artifactId><version>4.2</version></dependency>

源代碼

HTTPResponse

package cn.edu.zstu.myzstu.utils.httpclient; import java.io.Serializable; /*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-07-12 09:52*/ @SuppressWarnings("serial") public class HTTPResponse implements Serializable {/*** 響應(yīng)狀態(tài)碼*/private int statusCode;/*** 響應(yīng)數(shù)據(jù)*/private String content;public int getStatusCode() {return statusCode;}public void setStatusCode(int code) {this.statusCode = code;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public HTTPResponse() {super();}public HTTPResponse(int code) {super();this.statusCode = code;}public HTTPResponse(String content) {super();this.content = content;}public HTTPResponse(int code, String content) {super();this.statusCode = code;this.content = content;}@Overridepublic String toString() {return "HTTPResponse [code=" + statusCode + ", content=" + content + "]";} }

HTTPClientPool

package cn.edu.zstu.myzstu.utils.httpclient;import cn.edu.zstu.myzstu.utils.consts.Consts; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy;import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate;/*** Https忽略證書*/ public class HTTPClientPool {private static final String HTTP = "http";private static final String HTTPS = "https";private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = null;//連接池管理類private static SSLContextBuilder sslContextBuilder = null;//管理Https連接的上下文類private static BasicCookieStore basicCookieStore = null;static {basicCookieStore = new BasicCookieStore();try {sslContextBuilder = new SSLContextBuilder().loadTrustMaterial(null,new TrustStrategy() {@Overridepublic boolean isTrusted(X509Certificate[] x509Certificates, String s)throws CertificateException {// 信任所有站點(diǎn) 直接返回truereturn true;}});//"SSLv2Hello", "SSLv3", "TLSv1"sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),new String[]{"TLSv1.2"},null,NoopHostnameVerifier.INSTANCE);Registry<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create().register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslConnectionSocketFactory).build();poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registryBuilder);poolingHttpClientConnectionManager.setMaxTotal(200);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (KeyStoreException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();}}/*** 獲取連接** @return* @throws Exception*/public static CloseableHttpClient getHttpClient() throws Exception {CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).setConnectionManager(poolingHttpClientConnectionManager).setConnectionManagerShared(true).setDefaultCookieStore(basicCookieStore).setUserAgent(Consts.AGENT).build();return httpClient;}/*** 獲取關(guān)聯(lián)上下文的連接* @param basicCookieStore Cookie* @return* @throws Exception*/public static CloseableHttpClient getHttpClientWithContext(BasicCookieStore basicCookieStore) throws Exception {CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).setConnectionManager(poolingHttpClientConnectionManager).setConnectionManagerShared(true).setDefaultCookieStore(basicCookieStore).setUserAgent(Consts.AGENT).build();return httpClient;} }

HTTPClientUtil

package cn.edu.zstu.myzstu.utils.httpclient;import cn.edu.zstu.myzstu.utils.consts.Consts; import org.apache.commons.collections4.MapUtils; import org.apache.http.*; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.*; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils;import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set;/*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-07-19 10:12*/ public class HTTPClientUtil {private static Logger logger = LoggerFactory.getLogger(HTTPClientUtil.class);private static String ENCODING = Consts.ENCODING;private static RequestConfig requestConfig;private static int CONNECTION_REQUEST_TIMEOUT=1000*10;private static int CONNECT_TIMEOUT=1000*10;private static int SOCKET_TIMEOUT=1000*10;private static boolean REDIRECTS_ENABLED=false;/*** 靜態(tài)代碼塊*/static{requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).setRedirectsEnabled(REDIRECTS_ENABLED).build();}/*** Set URI* @param httpRequest* @param url* @param params* @throws URISyntaxException* @throws MalformedURLException*/private static void setParams(HttpRequestBase httpRequest,String url,Map<String, String> params)throws URISyntaxException, MalformedURLException {URIBuilder urlbuilder = new URIBuilder(url);if (MapUtils.isNotEmpty(params)) {// Set paramsfor (Map.Entry<String, String> stringStringEntry : params.entrySet()) {urlbuilder.setParameter(stringStringEntry.getKey(), stringStringEntry.getValue());}}logger.info(urlbuilder.build().toURL().toString());httpRequest.setURI(urlbuilder.build());}/*** Set Header* @param httpRequest 請(qǐng)求* @param headers 請(qǐng)求頭數(shù)據(jù)*/private static void setHeaders(HttpRequestBase httpRequest,Map<String, String> headers){// 封裝請(qǐng)求頭if (MapUtils.isNotEmpty(headers)) {Set<Map.Entry<String, String>> entrySet = headers.entrySet();for (Map.Entry<String, String> entry : entrySet) {// 設(shè)置到請(qǐng)求頭到HttpRequestBase對(duì)象中httpRequest.setHeader(entry.getKey(), entry.getValue());}}}/*** Description: 封裝請(qǐng)求參數(shù)* @param httpRequest 請(qǐng)求* @param type 參數(shù)類型* @param params 參數(shù)** @throws UnsupportedEncodingException*/private static void setEntity(HttpEntityEnclosingRequestBase httpRequest,String type,Map<String, String> params)throws UnsupportedEncodingException {// 封裝請(qǐng)求參數(shù)if (MapUtils.isNotEmpty(params)) {List<NameValuePair> nvps = new ArrayList<NameValuePair>();Set<Map.Entry<String, String>> entrySet = params.entrySet();for (Map.Entry<String, String> entry : entrySet) {nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}// 設(shè)置到請(qǐng)求的http對(duì)象中httpRequest.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));}}/*** Post Request* @param url URL* @param header 請(qǐng)求頭參數(shù)* @param params URL參數(shù)* @param formData 表單參數(shù)* @return HTTPResponse*/protected static HTTPResponse doPostRequest(String url,Map<String, String> header,Map<String, String> params,Map<String, String> formData,HttpClientContext httpClientContext) {CloseableHttpClient httpClient = null;HTTPResponse httpResponse=null;try {httpClient = HTTPClientPool.getHttpClient();HttpPost httpPost = new HttpPost();httpPost.setConfig(requestConfig);setParams(httpPost,url,params);setHeaders(httpPost,header);setEntity(httpPost,"form-data",formData);//發(fā)起請(qǐng)求httpResponse=getResponse(httpClient,httpPost,httpClientContext);} catch (Exception e) {e.printStackTrace();}return httpResponse;}/*** Get Request* @param url URL* @param header 請(qǐng)求頭參數(shù)* @param params URL參數(shù)* @return HTTPResponse*/protected static HTTPResponse doGetRequest(String url,Map<String, String> header,Map<String, String> params,HttpClientContext httpClientContext) {CloseableHttpClient httpClient = null;HTTPResponse httpResponse=null;try {httpClient = HTTPClientPool.getHttpClient();HttpGet httpGet = new HttpGet();httpGet.setConfig(requestConfig);setParams(httpGet,url,params);setHeaders(httpGet,header);//發(fā)起請(qǐng)求httpResponse=getResponse(httpClient,httpGet,httpClientContext);} catch (Exception e) {e.printStackTrace();}return httpResponse;}/*** 發(fā)送get請(qǐng)求;核心方法* @param url* @param headers* @param params* @return* @throws Exception*/public static HTTPResponse doGet(String url,Map<String, String> headers,Map<String, String> params)throws Exception {return doGetRequest(url,headers,params,null);}/*** 發(fā)送Post請(qǐng)求;核心方法* @param url* @param headers* @param params* @param formData* @return* @throws Exception*/public static HTTPResponse doPost(String url,Map<String, String> headers,Map<String, String> params,Map<String,String> formData)throws Exception {return doPostRequest(url,headers,params,formData,null);}/*** 發(fā)送get請(qǐng)求;不帶請(qǐng)求頭和請(qǐng)求參數(shù)* @param url 請(qǐng)求地址* @throws Exception*/public static HTTPResponse doGet(String url)throws Exception {return doGet(url, null, null);}/*** 發(fā)送get請(qǐng)求;帶請(qǐng)求參數(shù)** @param url 請(qǐng)求地址* @param params 請(qǐng)求參數(shù)集合* @throws Exception*/public static HTTPResponse doGet(String url,Map<String, String> params)throws Exception {return doGet(url, null, params);}/*** 發(fā)送post請(qǐng)求;不帶請(qǐng)求頭和請(qǐng)求參數(shù)** @param url 請(qǐng)求地址* @return* @throws Exception*/public static HTTPResponse doPost(String url)throws Exception {return doPost(url, null, null,null);}/*** 發(fā)送post請(qǐng)求;帶請(qǐng)求參數(shù)** @param url 請(qǐng)求地址* @param fromData 參數(shù)集合* @return* @throws Exception*/public static HTTPResponse doPost(String url,Map<String, String> fromData)throws Exception {return doPost(url, null, null,fromData);}/*** 發(fā)送post請(qǐng)求;帶請(qǐng)求參數(shù)* @param url 請(qǐng)求地址* @param params* @param fromData 參數(shù)集合* @return* @throws Exception*/public static HTTPResponse doPost(String url,Map<String, String> params,Map<String, String> fromData)throws Exception {return doPost(url, null, params,fromData);}/**** @param url* @param saveUrl* @return* @throws Exception*/public static boolean download(String url,String saveUrl) throws Exception {CloseableHttpClient httpClient = null;CloseableHttpResponse httpResponse = null;try{httpClient = HTTPClientPool.getHttpClient();HttpGet httpGet = new HttpGet(url);httpGet.setConfig(requestConfig);httpResponse = httpClient.execute(httpGet);HttpEntity httpEntity = httpResponse.getEntity();FileOutputStream fileOut=null;try{fileOut = new FileOutputStream(saveUrl);httpEntity.writeTo(fileOut);}catch (IOException e){e.printStackTrace();return false;}finally {if(fileOut!=null){fileOut.close();}}}catch (Exception e){e.printStackTrace();return false;}finally {closeConnection(httpClient, httpResponse);}return true;}/***發(fā)送請(qǐng)求,處理請(qǐng)求數(shù)據(jù)*/public static HTTPResponse getResponse(CloseableHttpClient httpClient,HttpRequestBase httpMethod,HttpClientContext httpClientContext) {CloseableHttpResponse response = null;try {response = httpClient.execute(httpMethod,httpClientContext);if(response == null || response.getStatusLine() == null){return new HTTPResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR);}String content = EntityUtils.toString(response.getEntity(), ENCODING);HTTPResponse httpResponse = new HTTPResponse(response.getStatusLine().getStatusCode());if(response.getStatusLine().getStatusCode()==HttpStatus.SC_MOVED_TEMPORARILY){Header[] allHeaders = response.getAllHeaders();for (Header headerpair : allHeaders) {if(headerpair.getName().equals("Location")){httpResponse.setContent( headerpair.getValue());break;}}if(StringUtils.isEmpty(httpResponse.getContent())){httpResponse.setContent(content);}}else{httpResponse.setContent(content);}return httpResponse;}catch (Exception e){e.printStackTrace();return new HTTPResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR);}finally {closeConnection(httpClient,response);}}/*** 關(guān)掉連接釋放資源* @param httpClient* @param httpResponse*/private static void closeConnection(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) {if (httpClient != null) {try {httpClient.close();} catch (IOException e) {e.printStackTrace();throw new RuntimeException("關(guān)閉Connection錯(cuò)誤!");}}if (httpResponse != null) {try {httpResponse.close();} catch (IOException e) {e.printStackTrace();throw new RuntimeException("關(guān)閉Response錯(cuò)誤!");}}} }

HTTPContext?

package cn.edu.zstu.myzstu.utils.httpclient;import org.apache.commons.collections4.MapUtils; import org.apache.http.client.CookieStore; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.cookie.BasicClientCookie;import java.util.Date; import java.util.Map;/*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-07-19 10:06*/ public class HTTPContext{private HttpClientContext httpClientContext;public HTTPContext() {CookieStore cookieStore = new BasicCookieStore();httpClientContext = HttpClientContext.create();httpClientContext.setCookieStore(cookieStore);}public HTTPContext(Map<String,String> cookies) {if (MapUtils.isNotEmpty(cookies)) {CookieStore cookieStore = new BasicCookieStore();httpClientContext = HttpClientContext.create();// Set paramsfor (Map.Entry<String, String> cookieMap : cookies.entrySet()) {// 發(fā)送自定義cookie:(new了一個(gè)對(duì)象之后可以設(shè)置多種屬性。)BasicClientCookie cookie = new BasicClientCookie(cookieMap.getKey(),cookieMap.getValue());// new a cookiecookie.setDomain("domain");cookie.setExpiryDate(new Date());// set the properties of the cookiecookieStore.addCookie(cookie);}httpClientContext.setCookieStore(cookieStore);}else{new HTTPContext();}}/*** 發(fā)送get請(qǐng)求;核心方法*/public HTTPResponse doGet(String url,Map<String, String> headers,Map<String, String> params) throws Exception {return HTTPClientUtil.doGetRequest(url, headers, params,httpClientContext);}/*** 發(fā)送Post請(qǐng)求;核心方法*/public HTTPResponse doPost(String url,Map<String, String> headers,Map<String, String> params,Map<String,String> formData) throws Exception {return HTTPClientUtil.doPostRequest(url, headers, params,formData,httpClientContext);}/*** 發(fā)送get請(qǐng)求;不帶請(qǐng)求頭和請(qǐng)求參數(shù)* @param url 請(qǐng)求地址* @throws Exception*/public HTTPResponse doGet(String url)throws Exception {return doGet(url, null, null);}/*** 發(fā)送get請(qǐng)求;帶請(qǐng)求參數(shù)** @param url 請(qǐng)求地址* @param params 請(qǐng)求參數(shù)集合* @throws Exception*/public HTTPResponse doGet(String url,Map<String, String> params)throws Exception {return doGet(url, null, params);}/*** 發(fā)送post請(qǐng)求;不帶請(qǐng)求頭和請(qǐng)求參數(shù)** @param url 請(qǐng)求地址* @return* @throws Exception*/public HTTPResponse doPost(String url)throws Exception {return doPost(url, null, null,null);}/*** 發(fā)送post請(qǐng)求;帶請(qǐng)求參數(shù)** @param url 請(qǐng)求地址* @param fromData 參數(shù)集合* @return* @throws Exception*/public HTTPResponse doPost(String url,Map<String, String> fromData)throws Exception {return doPost(url, null, null,fromData);}/*** 發(fā)送post請(qǐng)求;帶請(qǐng)求參數(shù)* @param url 請(qǐng)求地址* @param params* @param fromData 參數(shù)集合* @return* @throws Exception*/public HTTPResponse doPost(String url,Map<String, String> params,Map<String, String> fromData)throws Exception {return doPost(url, null, params,fromData);} }

測(cè)試

package cn.edu.zstu.myzstu.utils.test;import cn.edu.zstu.myzstu.utils.httpclient.HTTPClientUtil; import cn.edu.zstu.myzstu.utils.httpclient.HTTPResponse; import org.junit.jupiter.api.Test;/*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-07-19 12:39*/ public class MainTest {@Testpublic void httpTest() throws Exception {HTTPResponse httpResponse1 = HTTPClientUtil.doGet("https://www.baidu.com/");System.out.println(httpResponse1);HTTPResponse httpResponse2 = HTTPClientUtil.doPost("https://www.baidu.com/");System.out.println(httpResponse2);} }

參考文章

https://shentuzhigang.blog.csdn.net/article/details/104274609

https://blog.csdn.net/qq_28165595/article/details/78885775

https://blog.csdn.net/u010928589/article/details/84565843

https://blog.csdn.net/coqcnbkggnscf062/article/details/79412732

https://www.cnblogs.com/relax-zw/p/9883959.html

https://www.cnblogs.com/jason_chen/p/4664160.html

?

總結(jié)

以上是生活随笔為你收集整理的JAVA——保持cookie登录状态的HttpClient封装工具类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。