package com.util;

 import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpStatus;
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.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
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.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; /**
* commons-httpclient(停更)与httpclient(继续升级中)
*
* HTTP连接池请求,支持http和https请求,
* <p>
* 基于org.apache.httpcomponents.httpcore<version>4.4.10</version>
* </p>
* <p>
* 基于org.apache.httpcomponents.httpclient<version>4.5.6</version>
* </p>
*
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class HttpClientPoolUtil {
private static final String ENCODING = "UTF-8";
public static final int DEFAULT_CONNECT_TIMEOUT = 6000;
public static final int DEFAULT_READ_TIMEOUT = 6000;
public static final int DEFAULT_CONNECT_REQUEST_TIMEOUT = 6000;
private static final int MAX_TOTAL = 64;
private static final int MAX_PER_ROUTE = 32;
private static final RequestConfig requestConfig;
private static final PoolingHttpClientConnectionManager connectionManager;
private static final HttpClientBuilder httpBuilder;
private static final CloseableHttpClient httpClient;
private static final CloseableHttpClient httpsClient;
private static SSLContext sslContext; static {
try {
sslContext = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] {tm}, null);
} catch (Exception e) {
e.printStackTrace();
}
} static {
requestConfig = RequestConfig.custom().setSocketTimeout(DEFAULT_READ_TIMEOUT).setConnectTimeout(DEFAULT_CONNECT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_CONNECT_REQUEST_TIMEOUT).build();
@SuppressWarnings("deprecation")
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", new PlainConnectionSocketFactory())
.register("https", new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))
.build();
connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(MAX_TOTAL);
connectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
httpBuilder = HttpClientBuilder.create();
httpBuilder.setDefaultRequestConfig(requestConfig);
httpBuilder.setConnectionManager(connectionManager);
httpClient = httpBuilder.build();
httpsClient = httpBuilder.build();
} /**
* GET
*
* @param url
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doGet(String url)
throws Exception {
return doGet(url, false);
} /**
* GET
*
* @param url
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doGet(String url, boolean https)
throws Exception {
return doGet(url, null, null, https);
} /**
* GET
*
* @param url
* @param params
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doGet(String url, Map<String, String> params, boolean https)
throws Exception {
return doGet(url, null, params, https);
} /**
* GET
*
* @param url
* @param headers
* @param params
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params, boolean https)
throws Exception {
// 创建访问的地址
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 创建HTTP对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setConfig(requestConfig);
// 设置请求头
setHeader(headers, httpGet);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
if (https) {
return getHttpClientResult(httpResponse, httpsClient, httpGet);
} else {
return getHttpClientResult(httpResponse, httpClient, httpGet);
}
} finally {
httpGet.releaseConnection();
release(httpResponse);
}
} /**
* POST不带参数
*
* @param url
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doPost(String url)
throws Exception {
return doPost(url, Boolean.FALSE);
} /**
* @param url
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doPost(String url, boolean https)
throws Exception {
return doPost(url, null, (Map<String, String>)null, https);
} /**
* 带请求参数
*
* @param url
* @param params
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doPost(String url, Map<String, String> params, boolean https)
throws Exception {
return doPost(url, null, params, https);
} /**
* POST
*
* @param url
* @param headers
* @param params
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params, boolean https)
throws Exception {
// 创建HTTP对象
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
// 设置请求头
setHeader(headers, httpPost);
// 封装请求参数
setParam(params, httpPost);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
if (https) {
return getHttpClientResult(httpResponse, httpsClient, httpPost);
} else {
return getHttpClientResult(httpResponse, httpClient, httpPost);
}
} finally {
httpPost.releaseConnection();
release(httpResponse);
}
} /**
* POST请求JSON
*
* @param url
* @param headers
* @param json
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doPost(String url, Map<String, String> headers, String json, boolean https)
throws Exception {
// 创建HTTP对象
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
// 设置请求头
setHeader(headers, httpPost);
StringEntity stringEntity = new StringEntity(json, ENCODING);
stringEntity.setContentEncoding(ENCODING);
httpPost.setEntity(stringEntity);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
if (https) {
return getHttpClientResult(httpResponse, httpsClient, httpPost);
} else {
return getHttpClientResult(httpResponse, httpClient, httpPost);
}
} finally {
httpPost.releaseConnection();
release(httpResponse);
}
} /**
* 发送put请求;不带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url)
throws Exception {
return doPut(url);
} /**
* 发送put请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url, Map<String, String> params)
throws Exception {
// CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
// RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPut.setConfig(requestConfig);
setParam(params, httpPut);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpPut);
} finally {
httpPut.releaseConnection();
release(httpResponse);
}
} /**
* 不带请求参数
*
* @param url
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doDelete(String url)
throws Exception {
// CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
// RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpDelete.setConfig(requestConfig);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpDelete);
} finally {
httpDelete.releaseConnection();
release(httpResponse);
}
} /**
* 带请求参数
*
* @param url
* @param params
* @param https
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult doDelete(String url, Map<String, String> params, boolean https)
throws Exception {
if (params == null) {
params = new HashMap<String, String>();
}
params.put("_method", "delete");
return doPost(url, params, https);
} /**
* 设置封装请求头
*
* @param params
* @param httpMethod
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static void setHeader(Map<String, String> params, HttpRequestBase httpMethod) {
// 封装请求头
if (MapUtils.isNotEmpty(params)) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
// 设置到请求头到HttpRequestBase对象中
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
} /**
* 封装请求参数
*
* @param params
* @param httpMethod
* @throws UnsupportedEncodingException
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static void setParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
throws UnsupportedEncodingException {
// 封装请求参数
if (MapUtils.isNotEmpty(params)) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 设置到请求的http对象中
httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
}
} /**
* 获得响应结果
*
* @param httpResponse
* @param httpClient
* @param httpMethod
* @return
* @throws Exception
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient, HttpRequestBase httpMethod)
throws Exception {
// 执行请求
httpResponse = httpClient.execute(httpMethod);
// 获取返回结果
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = "";
if (httpResponse.getEntity() != null) {
content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
}
return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
}
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
} /**
* 释放资源
*
* @param httpResponse
* @throws IOException
* @author Henry(fba02)
* @version [版本号, 2019年12月8日]
* @see [类、类#方法、类#成员]
*/
public static void release(CloseableHttpResponse httpResponse)
throws IOException {
// 释放资源
if (httpResponse != null) {
httpResponse.close();
}
}
} package com.util; import java.io.Serializable; @SuppressWarnings("serial")
public class HttpClientResult implements Serializable {
/**
* 响应状态码
*/
private int code; /**
* 响应数据
*/
private String content; public int getCode() {
return code;
} public void setCode(int code) {
this.code = code;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} public HttpClientResult() {
super();
} public HttpClientResult(int code) {
super();
this.code = code;
} public HttpClientResult(int code, String content) {
super();
this.code = code;
this.content = content;
} @Override
public String toString() {
return "HttpClientResult [code=" + code + ", content=" + content + "]";
}
}

基于httpclient的一些常用方法封装的更多相关文章

  1. HttpClient 常用方法封装

    简介 在平时写代码中,经常需要对接口进行访问,对于 http 协议 rest 风格的接口请求,大多使用 HttpClient 工具进行编写,想着方便就寻思着把一些常用的方法进行封装,便于平时快速的使用 ...

  2. 基于表单数据的封装,泛型,反射以及使用BeanUtils进行处理

    在Java Web开发过程中,会遇到很多的表单数据的提交和对表单数据的处理.而每次都需要对这些数据的字段进行一个一个的处理就显得尤为繁琐,在Java语言中,面向对象的存在目的便是为了消除重复代码,减少 ...

  3. java Map常用方法封装

      java Map常用方法封装 CreationTime--2018年7月16日15点59分 Author:Marydon 1.准备工作 import java.util.HashMap; impo ...

  4. 基于iOS 10、realm封装的下载器

    代码地址如下:http://www.demodashi.com/demo/11653.html 概要 在决定自己封装一个下载器前,我本以为没有那么复杂,可在实际开发过程中困难重重,再加上iOS10和X ...

  5. Http请求封装(对HttpClient类的进一步封装,使之调用更方便。另外,此类管理唯一的HttpClient对象,支持线程池调用,效率更高)

    package com.ad.ssp.engine.common; import java.io.IOException; import java.util.ArrayList; import jav ...

  6. 适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

    适用于app.config与web.config的ConfigUtil读写工具类   之前文章:<两种读写配置文件的方案(app.config与web.config通用)>,现在重新整理一 ...

  7. 基于HttpClient实现网络爬虫~以百度新闻为例

    转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/40891791 基于HttpClient4.5实现网络爬虫请訪问这里:http:/ ...

  8. 基于HttpClient 4.3的可訪问自签名HTTPS网站的新版工具类

    本文出处:http://blog.csdn.net/chaijunkun/article/details/40145685,转载请注明.因为本人不定期会整理相关博文,会对相应内容作出完好.因此强烈建议 ...

  9. 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)

    近期工作中有使用到 MongoDb作为日志持久化对象,需要实现对MongoDb的增.删.改.查,但由于MongoDb的版本比较新,是2.4以上版本的,网上已有的一些MongoDb Helper类都是基 ...

随机推荐

  1. Antd 修改主题颜色填坑记录

    首先,让我想说的是,现在有很多的更新,网上的一些也有的没用了, 接下来让我来分享一些我的解决方法,时间:2018.12/18. 1.和网上的一样,我用的是creat-react-app创建的项目,修改 ...

  2. logger日志接口SLF4J

    SLF4J只是一个接口,可以实现程序的解藕.SLF4J可以与log4j.logback.jdk等日志系统结合,以及在这些日志系统之间切换. 使用maven导入各个日志系统的jar包.需要注意的是要写相 ...

  3. 就为了一个原子操作,其他CPU核心罢工了

    i++问题 "阿Q赶快回去吧,隔壁二号车间的虎子说我们改了他们的数据,上门来闹事了" 由于老K的突然出现,我不得不提前结束与小黑的交流,赶回了CPU一号车间. 见到我回来,虎子立刻 ...

  4. UIStackView上手教程

    https://www.jianshu.com/p/19fbf3ee2840 https://www.cnblogs.com/bokeyuanlibin/p/5693575.html https:// ...

  5. wordpress评论回复邮件通知功能

    安装插件登录后台——点击“插件”——“安装插件”——按关键字搜索“Comment Reply Notification”——点击“现在安装”安装好后启用插件.如下图所示: 配置Comment Repl ...

  6. Springboot整合MybatisPlus(超详细)完整教程~

    新建springboot项目 开发工具:idea2019.2,maven3 pom.xml <dependency> <groupId>org.springframework. ...

  7. vue中生命周期

    1,说器生命周期,总觉得有熟悉,又陌生,直到看到一道面试题,问父子组件的生命周期的执行顺序,我擦,真没太注意啊,不知道. 2,网上搜了一下,说法是有点像洋葱圈的形式,由外到内,在到外,因为就像一个盒子 ...

  8. 【QT】利用pyqt5实现简单界面

    Topic: 利用pyqt5编写简单界面Env:win10 + Pycharm2018 + Python 3.6.8Date: 2019/4/29 by hw_Chen2018            ...

  9. 盘点Mysql的登陆方式

    前置知识 我们想登陆到mysql中前提是肯定需要一个用户名和密码:比如 root root 在mysql中用户的信息会存放在 mysql数据库下的 user表中 可以 use mysql 然后sele ...

  10. [批处理教程之Shell]001.文本处理

    在计算机科学中,Shell俗称壳(用来区别于核),是指“提供使用者使用界面”的软件(命令解析器).它类似于DOS下的command和后来的cmd.exe.它接收用户命令,然后调用相应的应用程序. 同时 ...