在日常开发中,我们经常需要通过http协议去调用网络内容,虽然java自身提供了net相关工具包,但是其灵活性和功能总是不如人意,于是有人专门搞出一个httpclient类库,来方便进行Http操作。简单的对httpcient的简单操作封装成一个工具类,统一放在项目的工具包中,在使用的时候直接从工具包中调用,不需要写冗余代码。

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 {/*** 响应状态码*/private int statusCode;/*** 响应数据*/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 {//                    信任所有站点 直接返回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;}/*** 获取关联上下文的连接* @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;/*** 静态代码块*/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 请求* @param headers 请求头数据*/private static void setHeaders(HttpRequestBase httpRequest,Map<String, String> headers){// 封装请求头if (MapUtils.isNotEmpty(headers)) {Set<Map.Entry<String, String>> entrySet = headers.entrySet();for (Map.Entry<String, String> entry : entrySet) {// 设置到请求头到HttpRequestBase对象中httpRequest.setHeader(entry.getKey(), entry.getValue());}}}/*** Description: 封装请求参数* @param httpRequest 请求* @param type 参数类型* @param params 参数** @throws UnsupportedEncodingException*/private static void setEntity(HttpEntityEnclosingRequestBase httpRequest,String type,Map<String, String> params)throws UnsupportedEncodingException {// 封装请求参数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()));}// 设置到请求的http对象中httpRequest.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));}}/*** Post Request* @param url URL* @param header 请求头参数* @param params URL参数* @param formData 表单参数* @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);//发起请求httpResponse=getResponse(httpClient,httpPost,httpClientContext);} catch (Exception e) {e.printStackTrace();}return  httpResponse;}/*** Get Request* @param url URL* @param header 请求头参数* @param params URL参数* @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);//发起请求httpResponse=getResponse(httpClient,httpGet,httpClientContext);} catch (Exception e) {e.printStackTrace();}return  httpResponse;}/*** 发送get请求;核心方法* @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);}/*** 发送Post请求;核心方法* @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);}/*** 发送get请求;不带请求头和请求参数* @param url 请求地址* @throws Exception*/public static HTTPResponse doGet(String url)throws Exception {return doGet(url, null, null);}/*** 发送get请求;带请求参数** @param url 请求地址* @param params 请求参数集合* @throws Exception*/public static HTTPResponse doGet(String url,Map<String, String> params)throws Exception {return doGet(url, null, params);}/*** 发送post请求;不带请求头和请求参数** @param url 请求地址* @return* @throws Exception*/public static HTTPResponse doPost(String url)throws Exception {return doPost(url, null, null,null);}/*** 发送post请求;带请求参数** @param url 请求地址* @param fromData 参数集合* @return* @throws Exception*/public static HTTPResponse doPost(String url,Map<String, String> fromData)throws Exception {return doPost(url, null, null,fromData);}/*** 发送post请求;带请求参数* @param url 请求地址* @param params* @param fromData 参数集合* @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;}/***发送请求,处理请求数据*/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);}}/*** 关掉连接释放资源* @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("关闭Connection错误!");}}if (httpResponse != null) {try {httpResponse.close();} catch (IOException e) {e.printStackTrace();throw new RuntimeException("关闭Response错误!");}}}
}

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()) {//  发送自定义cookie:(new了一个对象之后可以设置多种属性。)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();}}/*** 发送get请求;核心方法*/public  HTTPResponse doGet(String url,Map<String, String> headers,Map<String, String> params) throws Exception {return HTTPClientUtil.doGetRequest(url, headers, params,httpClientContext);}/*** 发送Post请求;核心方法*/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);}/*** 发送get请求;不带请求头和请求参数* @param url 请求地址* @throws Exception*/public HTTPResponse doGet(String url)throws Exception {return doGet(url, null, null);}/*** 发送get请求;带请求参数** @param url 请求地址* @param params 请求参数集合* @throws Exception*/public HTTPResponse doGet(String url,Map<String, String> params)throws Exception {return doGet(url, null, params);}/*** 发送post请求;不带请求头和请求参数** @param url 请求地址* @return* @throws Exception*/public HTTPResponse doPost(String url)throws Exception {return doPost(url, null, null,null);}/*** 发送post请求;带请求参数** @param url 请求地址* @param fromData 参数集合* @return* @throws Exception*/public HTTPResponse doPost(String url,Map<String, String> fromData)throws Exception {return doPost(url, null, null,fromData);}/*** 发送post请求;带请求参数* @param url 请求地址* @param params* @param fromData 参数集合* @return* @throws Exception*/public HTTPResponse doPost(String url,Map<String, String> params,Map<String, String> fromData)throws Exception {return doPost(url, null, params,fromData);}
}

测试

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

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

  1. JAVA——HttpClient封装工具类

    在日常开发中,我们经常需要通过http协议去调用网络内容,虽然java自身提供了net相关工具包,但是其灵活性和功能总是不如人意,于是有人专门搞出一个httpclient类库,来方便进行Http操作. ...

  2. JAVA——Okhttp封装工具类

    基本概念 OKhttp:一个处理网络请求的开源项目,是安卓端最火热的轻量级框架. Maven <!--OK HTTP Client--><dependency><grou ...

  3. JAVA之旅(五)——this,static,关键字,main函数,封装工具类,生成javadoc说明书,静态代码块...

    JAVA之旅(五)--this,static,关键字,main函数,封装工具类,生成javadoc说明书,静态代码块 周末收获颇多,继续学习 一.this关键字 用于区分局部变量和成员变量同名的情况 ...

  4. HttpClient Utils工具类的编写方法分享

    转自: HttpClient Utils工具类的编写方法分享 HttpClient简介: HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功 ...

  5. android文件读取工具类,Android 下读取Assets Properties操作封装工具类

    Android 下读取Assets Properties操作封装工具类 发布时间:2018-06-03作者:laosun阅读(2081) 为了方便使用,首先创建BaseApplication类,如下所 ...

  6. 数据库MySQL基础---JDBC开发步骤--JDBC封装工具类--PreparedStatement实现CRUD操作

    JDBC简介 1.JDBC定义Java数据库连接(Java Database Connectivity,简称JDBC):是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询 ...

  7. java 自定义json解析注解 复杂json解析 工具类

    java 自定义json解析注解 复杂json解析 工具类 目录 java 自定义json解析注解 复杂json解析 工具类 1.背景 2.需求-各式各样的json 一.一星难度json[json对象 ...

  8. java sm3国密算法加密、验证工具类

    java sm3国密算法加密.验证工具类 说明 maven依赖 完整代码 测试 说明 由于本人并不专于算法和密码学,所以如果发现工具类存在问题或者可优化地方,欢迎评论处提出. 工具类也可以直接使用封装 ...

  9. 如何调用封装工具类调用网上接口查询工作日

    如何调用封装工具类调用网上接口查询工作日 这里的编辑器是STS,用的springboot集成环境: 先引进pom.xml依赖包 <?xml version="1.0" enc ...

最新文章

  1. 小程序框架之wepy报错问题
  2. 插入排序之——希尔排序(c/c++)
  3. 切换debian8系统语言环境
  4. SpringMVC RequestMapping注解详解
  5. 将std::string字符串格式的数字转换为int类型的数字
  6. Ubuntu 挂载新磁盘
  7. 对抗学习新进展:MIT和微软联合出品“元对抗扰动”
  8. Educational Codeforces Round 64 Div.2 D - 0-1-Tree
  9. 大数据学习笔记06:伪分布式Hadoop
  10. Security+ 学习笔记30 云计算构建模块
  11. Vb 6.0 ado连接mysql_VB使用ADO操作Access数据库
  12. JUL配置文件进行相关配置
  13. 8421 5421 2421 余3码
  14. 1949年的国庆节(10月1日)是星期六.......
  15. 利用python的matplotlib绘制分布图
  16. joycon手柄拆解_爱活电刑室 | 撬开海拉尔的大门! 任天堂Switch全拆解
  17. Linux软件包管理— rpm软件包查询
  18. ZedBoard的初步学习-通信设置
  19. 今日总结:错误码配置,关于TXT文件下载问题
  20. element 实现自定义 宫格 布局

热门文章

  1. SQL Server 2005学习笔记
  2. iis php配置内部错误,iis 500 内部服务器错误 php
  3. delphi cxgrid读取本地image_技术讨论 | PHP本地文件包含漏洞GetShell
  4. mysql的limit和or_面试官:谈谈MySQL的limit用法、逻辑分页和物理分页
  5. python文件操作解码_python基础3之文件操作、字符编码解码、函数介绍
  6. php 精品课程,php51精品课程高级版
  7. android studio gradle配置_Unity打包Android最全攻略(含完整流程及常见问题)
  8. python读取raw数据文件_Python 读写文件中数据
  9. 给定一个投资组合的收益序列,以沪深300作为参照,分解该投资组合的α和β
  10. 七、Java编码字符集和转义符介绍