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. TCP三次握手的seq和ack号的【正确】理解

    1 理论知识 先上一张图,TCP/IP详解第18章的这张图描述了一个正常的三次握手和四次挥手的状态迁移,以及seq.ack序号的变化. 基本状态看图就能了解,本文主要围绕序号的变化进行讲解. 1)se ...

  2. Mysql快速入门(看完这篇能够满足80%的日常开发)

    这是一篇mysql的学习笔记,整理结合了网上搜索的教程以及自己看的视频教程,看完这篇能够满足80%的日常开发了. 菜鸟教程:https://www.runoob.com/mysql/mysql-tut ...

  3. 你真的了解负载均衡中间件nginx吗?

    前言 nginx可所谓是如今最好用的软件级别的负载均衡了.通过nginx的高性能,并发能力强,占用内存下的特点,可以搭建高性能的代理服务.同时nginx还能作为web服务器,反向代理,动静分离服务器. ...

  4. 30分钟快速上手Docker,看这篇就对了!

    一.历史演化 1.演化史 2.物理机时代 2.1.图解 一个物理机上安装操作系统,然后直接运行我们的软件.也就是说你电脑上直接跑了一个软件,并没有开虚拟机什么的,资源极其浪费. 2.2.缺点 部署慢 ...

  5. Higher-Order Functions Fundamentals

    Higher-Order Functions A function that accepts and/or returns another function is called a higher-or ...

  6. Swiper的jquery动态渲染不能滑动

    <!-- 下面俩行代码就是解决异步加载数据导致swiper不轮播的关键 --> observer: true,//修改swiper自己或子元素时,自动初始化swiper observePa ...

  7. 分布式项目开发-springmvc.xmll基础配置

    基础步骤: 1 包扫描 2 驱动开发 3 视图解析器 4 文件上传解析器 5 拦截器 6 静态资源 <beans xmlns="http://www.springframework.o ...

  8. docker重启提示已存在一个容器的问题处理

    一.问题:在vmware虚拟机中测试以docker方式安装的prometheus,当重启虚拟机后,再次运行prometheus的执行文件,提示已有名称为prometheus的容器存在. 二.处理过程 ...

  9. Rocket - debug - TLDebugModuleInner - Hart Bus Access

    https://mp.weixin.qq.com/s/deNMEyJ1idJDVoZwwo0A1A 简单介绍TLDebugModuleInner中核心总线访问(Hart Bus Access). 参考 ...

  10. jchdl - GSL实例 - DFlipFlop(D触发器)

    https://mp.weixin.qq.com/s/7N3avTxTd2ZUnAcKg4w3Ig   D触发器对边沿敏感,只有当相应的边沿出现时,才会触发D的值传播到输出Q.   ​​ 引自:htt ...