1、关键 JAR 

<!--
《《===================》》
httpClient
《《===================》》
-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!--
《《===================》》
IO
《《===================》》
-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

2、封装工具类(HttpClientUtils)

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
// package com.tree.ztree_demo.httpclient; import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
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.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
/**
* @Description:HttpClientUtils 封装
* @author: MLQ
* @param:
* @return:
* @exception:
* @date: 2019/5/17 15:57
*/
public class HttpClientUtils {
private static Logger LOG = LoggerFactory.getLogger(HttpClientUtils.class);
private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
private static RequestConfig requestConfig;
private static final int MAX_TOTAL = 100;
private static final int MAX_TIMEOUT = 7000;
private static final int CONNECT_TIMEOUT = 10000;
private static final int SOCKET_TIMEOUT = 40000;
private static final String CHARSET = "UTF-8"; public HttpClientUtils() {
} public static String doGet(String url) throws Exception {
return doGet(url, new HashMap());
} public static String doGet(String url, Map<String, Object> params) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doGet url is null or '' ");
return result;
} else {
List<NameValuePair> pairList = new ArrayList(params.size());
Iterator var4 = params.entrySet().iterator(); while(var4.hasNext()) {
Entry<String, Object> entry = (Entry)var4.next();
NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
pairList.add(pair);
} CloseableHttpResponse response = null;
InputStream instream = null;
CloseableHttpClient httpclient = HttpClients.createDefault(); try {
URIBuilder URIBuilder = new URIBuilder(url);
URIBuilder.addParameters(pairList);
URI uri = URIBuilder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpclient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doGet statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var16) {
LOG.error("doGet IO ERROR :{}", var16.getMessage());
} catch (URISyntaxException var17) {
LOG.error("doGet URISyntaxException :{}", var17.getMessage());
} finally {
if (null != instream) {
instream.close();
} if (null != response) {
response.close();
} if (null != httpclient) {
httpclient.close();
} LOG.info("close instream response httpClient connection succ");
} return result;
}
} public static String doGet(String url, Map<String, Object> params, String charset) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doGet url is null or '' ");
return result;
} else {
List<NameValuePair> pairList = new ArrayList(params.size());
Iterator var5 = params.entrySet().iterator(); while(var5.hasNext()) {
Entry<String, Object> entry = (Entry)var5.next();
NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
pairList.add(pair);
} CloseableHttpResponse response = null;
InputStream instream = null;
CloseableHttpClient httpclient = HttpClients.createDefault(); try {
URIBuilder URIBuilder = new URIBuilder(url);
URIBuilder.addParameters(pairList);
URI uri = URIBuilder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpclient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doGet statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, charset);
}
} catch (IOException var17) {
LOG.error("doGet IO ERROR :{}", var17.getMessage());
} catch (URISyntaxException var18) {
LOG.error("doGet URISyntaxException :{}", var18.getMessage());
} finally {
if (null != instream) {
instream.close();
} if (null != response) {
response.close();
} if (null != httpclient) {
httpclient.close();
} LOG.info("close instream response httpClient connection succ");
} return result;
}
} public static String doPost(String apiUrl) throws Exception {
return doPost(apiUrl, (Map)(new HashMap()));
} public static String doPost(String url, Map<String, Object> params) throws Exception {
String result = null;
String param = "";
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPost url is null or '' ");
return result;
} else {
List<NameValuePair> pairList = new ArrayList(params.size());
Iterator var5 = params.entrySet().iterator(); while(var5.hasNext()) {
Entry<String, Object> entry = (Entry)var5.next();
NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
pairList.add(pair);
if (param.equals("")) {
param = (String)entry.getKey() + "=" + entry.getValue();
} else {
param = param + "&" + (String)entry.getKey() + "=" + entry.getValue();
}
} LOG.info("http请求地址:" + url + "?" + param);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null; try {
httpPost.setConfig(requestConfig);
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doPost statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
LOG.info("doPost Result:{}", result);
}
} catch (IOException var14) {
LOG.error("doPost ERROR :{}", var14.getMessage());
} finally {
if (null != instream) {
instream.close();
} if (null != response) {
response.close();
} if (null != httpClient) {
httpClient.close();
} LOG.info("close instream response httpClient connection succ");
} return result;
}
} public static String doPost(String url, String xml) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPost url is null or '' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null; try {
LOG.info("短信请求服务器地址:" + url + "?" + xml);
httpPost.setConfig(requestConfig);
httpPost.setEntity(new StringEntity(xml, "GBK"));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doPost statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var12) {
LOG.error("doPost ERROR :{}", var12.getMessage());
} finally {
if (null != instream) {
instream.close();
} if (null != response) {
response.close();
} if (null != httpClient) {
httpClient.close();
} LOG.info("close instream response httpClient connection succ");
} return result;
}
} public static String doPost(String url, Object json) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPostByJson url is null or '' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null; try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doPost statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var13) {
LOG.error("doPost BY JSON ERROR :{}", var13.getMessage());
} finally {
if (null != instream) {
instream.close();
} if (null != response) {
response.close();
} if (null != httpClient) {
httpClient.close();
} } return result;
}
} public static String doPostPay(String url, Object json) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPostByJson url is null or '' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null; try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("Accept", "application/json");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doPost statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var13) {
LOG.error("doPost BY JSON ERROR :{}", var13.getMessage());
} finally {
if (null != instream) {
instream.close();
} if (null != response) {
response.close();
} if (null != httpClient) {
httpClient.close();
} } return result;
}
} public static String doPostSSL(String apiUrl, Map<String, Object> params) throws Exception {
String result = null;
if (StringUtils.isEmpty(apiUrl)) {
LOG.info("warn:doPostSSL url is null or '' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
InputStream instream = null; try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList(params.size());
Iterator var8 = params.entrySet().iterator(); Entry entry;
while(var8.hasNext()) {
entry = (Entry)var8.next();
NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
pairList.add(pair);
} httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
LOG.info("doPostSSL statusCode:{}", statusCode);
entry = null;
return String.valueOf(entry);
} HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (Exception var14) {
LOG.error("doPostSSL ERROR :{}", var14.getMessage());
} finally {
if (null != instream) {
instream.close();
} if (null != response) {
response.close();
} if (null != httpClient) {
httpClient.close();
} LOG.info("close instream response httpClient connection succ");
} return result;
}
} public static String doPostSSL(String apiUrl, Object json) throws Exception {
String result = null;
if (StringUtils.isEmpty(apiUrl)) {
LOG.info("warn:doPostSSL By Json url is null or '' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
InputStream instream = null; HttpEntity entity;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
} return result;
} LOG.info("doPostSSL by json statusCode:{}", statusCode);
entity = null;
} catch (Exception var13) {
LOG.error("doPostSSL BY JSON ERROR :{}", var13.getMessage());
return result;
} finally {
if (null != instream) {
instream.close();
} if (null != response) {
response.close();
} if (null != httpClient) {
httpClient.close();
} LOG.info("close instream response httpClient connection succ");
} return String.valueOf(entity);
}
} private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null; try {
SSLContext sslContext = (new SSLContextBuilder()).loadTrustMaterial((KeyStore)null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
} public void verify(String host, SSLSocket ssl) throws IOException {
} public void verify(String host, X509Certificate cert) throws SSLException {
} public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
});
} catch (GeneralSecurityException var2) {
LOG.error("createSSLConnSocketFactory ERROR :{}", var2.getMessage());
} return sslsf;
} public static String doPostPay(String url, Object json, String authorization) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPostByJson url is null or '' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null; try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Authorization", authorization);
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doPost statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var14) {
LOG.error("doPost BY JSON ERROR :{}", var14.getMessage());
} finally {
if (null != instream) {
instream.close();
} if (null != response) {
response.close();
} if (null != httpClient) {
httpClient.close();
} } return result;
}
} public static String doPostPayUpgraded(String url, Object json, String authorization) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("新支付接口url不能为空!");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null; try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("Authorization", authorization);
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("新支付请求状态 statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var14) {
LOG.error("新支付接口发送异常:{}", var14.getMessage());
} finally {
if (null != instream) {
instream.close();
} if (null != response) {
response.close();
} if (null != httpClient) {
httpClient.close();
} } return result;
}
} static {
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(100);
Builder configBuilder = RequestConfig.custom();
configBuilder.setConnectTimeout(10000);
configBuilder.setSocketTimeout(40000);
configBuilder.setConnectionRequestTimeout(7000);
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
}
}

HttpClientUtils

直接拷贝就可以使用了。

coding++ :HttpClientUtils 封装的更多相关文章

  1. webdriver+expected_conditions二次封装

    结合这两种方法对代码做二次封装,可以提升脚本性能 例: #coding:utf-8 #封装元素方法from selenium import webdriverfrom selenium.webdriv ...

  2. 第二百六十七节,Tornado框架-分页封装模块

    Tornado框架-分页封装模块 框架引擎 #!/usr/bin/env python #coding:utf-8 import tornado.ioloop import tornado.web # ...

  3. 使用webdriverwait封装查找元素方法

    对于selenium原生的查找元素方法进行封装,在timeout规定时间内循环查找页面上有没有某个元素 这样封装的好处: 1.可以有效提高查找元素的效率,避免元素还没加载完就抛异常 2.相对于time ...

  4. python--面向对象之三个特性:封装、继承、多态

    一.面向对象简介 1.面向对象不是所有的情况都适用2.面向对象编程 a.定义类 class 类名: def 方法1(self, 参数名): 方法体 b.根据类创建对象,使用对象去执行类中的方法 obj ...

  5. python(函数封装)

    一:Python 自定义函数 函数示意图如下: 1.使用函数的好处: 代码重用 保持一致性,易维护 可扩展性 2.函数定义 函数定义的简单规则: 函数代码块以def关键词开头 后接函数标识符名称和圆括 ...

  6. python中协程

    在引出协成概念之前先说说python的进程和线程. 进程: 进程是正在执行程序实例.执行程序的过程中,内核会讲程序代码载入虚拟内存,为程序变量分配空间,建立 bookkeeping 数据结构,来记录与 ...

  7. python web的进化历程

    对于所有的Web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端. 阶段1 socket服务端和客户端都自己编写 实现访问8080端口,返回一个'hello wo ...

  8. iOS key value coding kvc在接收json数据与 model封装中的使用

    iOS key value coding  kvc在接收json数据与 model封装中的使用 使用 kvc 能够极大的简化代码工作,及以后的接口维护工作: 1:先创建MovieModel类.h和 . ...

  9. coding++ :JS对日期的神操作封装版

    格式化日期: /** * 格式化日期 * @param fmt 例如:yyyy-MM-dd 等 * @returns {*} * @constructor */ Date.prototype.Form ...

随机推荐

  1. 一起了解 .Net Foundation 项目 No.11

    .Net 基金会中包含有很多优秀的项目,今天就和笔者一起了解一下其中的一些优秀作品吧. 中文介绍 中文介绍内容翻译自英文介绍,主要采用意译.如与原文存在出入,请以原文为准. Microsoft Web ...

  2. 时间序列数据库(TSDB)初识与选择(InfluxDB、OpenTSDB、Druid、Elasticsearch对比)

    背景 这两年互联网行业掀着一股新风,总是听着各种高大上的新名词.大数据.人工智能.物联网.机器学习.商业智能.智能预警啊等等. 以前的系统,做数据可视化,信息管理,流程控制.现在业务已经不仅仅满足于这 ...

  3. 记一次苹果APP从账号续费到发布成功的历程

    一.一波三折的续费      最近公司开发的苹果APP的SSL证书到期了,计划重新发布一下该APP,已替换即将到期的SSL证书.近几年随着钉钉.企业微信等在线办公软件超级平台的出现,各企业都会选择其中 ...

  4. Mac使用brew安装MongoDB

    之前一直使用以下命令安装MongoDB,但是一直安装不上 brew install mongodb 后来看了官网,安装方法如下 brew tap mongodb/brew //这步不知道需不需要 br ...

  5. Css里的BFC

    一.BFC简介 BFC全称:Block Formatting Contexts (BFC,块级格式化上下文),就是 一个块级元素 的渲染显示规则 (可以把 BFC 理解为一个封闭的大箱子,,容器里面的 ...

  6. 《Javascript中 == 和 === 的区别》

    在js中 ==(相等运算符) 和 === (严格运算符)是两种判断两个变量是否相等的运算符. == :判断是否相等,忽略类型进行值的比较.(存在隐式类型转换的比较) ===:判断是否相等,先判断值是否 ...

  7. MyBatis-Plus不写任何resultMap和SQL执行一对一、一对多、多对多关联查询

    对于一对一,一对多的关联查询,Mybatis-Plus官方示例(mybatis-plus-sample-resultmap)在处理时,需要编写查询方法及配置resultMap,并且写SQL. 为了简化 ...

  8. 一致性hash算法之php实现

    源码地址:https://github.com/killallspree/myFrame/blob/master/framework/components/Flexihash.php

  9. 吐血干货,直播首屏耗时400ms以下的优化实践

    导读: 直播行业的竞争越来越激烈,进过18年这波洗牌后,已经度过了蛮荒暴力期,剩下的都是在不断追求体验.最近在帮做直播优化首开,通过多种方案并行,把首开降到500ms以下,希望能对大家有借鉴. 背景: ...

  10. vue基础----修饰符,watch,computed,method实例方法

    1.vue常用的修饰符,number,trim,number--->当作数字,trim-->去掉前后空格 2.methods与计算属性 computed 的相同与区别 <body&g ...