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. DataGirdView

    DataGridView知识点 简单示例 (1)代码 SqlDataAdapter da; DataSet ds; string sql ="select 列名 from 表名": ...

  2. date成字符串

    //获取当前时间 Date date=new Date(); System.out.println("当前date: "+date); //将时间转化成yyyy-MM-dd格式的字 ...

  3. MVC03

    1.添加model model 的作用是什么? 处理项目的数据模型,与数据库交互 .net推荐的处理数据的方式:使用 idd framework 1)新建model 右键models文件夹,选择添加, ...

  4. Windows下利用virtualenvwrapper指定python版本创建虚拟环境

    默认已安装virtualenvwrapper 一.添加环境变量(可选) 在系统环境变量中添加 WORKON_HOME ,用来指定新建的虚拟环境的存储位置,如过未添加,默认位置为 %USERPROFIL ...

  5. Java基础--方法的定义

    1.为什么要有方法? 方法(又叫函数)就是一段特定功能的代码块.方法提高程序的复用性和可读性. 比如,有了方法,我们可以把要重复使用的一段代码提炼出来,然后在每个需要执行这段代码的地方去调用即可. 2 ...

  6. BTrace实战

    BTrace在解决现场问题的时候非常有用. 1.概述 1.1下载 https://github.com/btraceio/btrace,最新版本是1.3.9 目前1.3.x系列最低支持JDK1.7,要 ...

  7. docker 学习(四)

    1.Dockerfile简介 1)什么是Dockerfile Dockerfile是一个包含用于组合映像的命令的文本文档.可以使用在命令行中调用任何命令. Docker通过读取Dockerfile中的 ...

  8. .Net Core 依赖注入手记

    .Net Core自身提供了一套简单的DI框架,能满足我们DI基本的需求.它依赖以下组件,需要从Nuget包下拉取. Microsoft.Extensions.DependencyInjection. ...

  9. ReentrantLock 源码分析以及 AQS (一)

    前言 JDK1.5 之后发布了JUC(java.util.concurrent),用于解决多线程并发问题.AQS 是一个特别重要的同步框架,很多同步类都借助于 AQS 实现了对线程同步状态的管理. A ...

  10. Docker极简部署Kafka+Zookeeper+ElasticStack

    之前写ELK部分时有朋友问有没有能一键部署的Kafka+ELK,写本文主要是填这个坑,基本上配置已经集中在一两个文件中了,理论上此配置支持ElasticStack 7.x所有版本 本文所有配置与代码均 ...