coding++ :HttpClientUtils 封装
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 封装的更多相关文章
- webdriver+expected_conditions二次封装
结合这两种方法对代码做二次封装,可以提升脚本性能 例: #coding:utf-8 #封装元素方法from selenium import webdriverfrom selenium.webdriv ...
- 第二百六十七节,Tornado框架-分页封装模块
Tornado框架-分页封装模块 框架引擎 #!/usr/bin/env python #coding:utf-8 import tornado.ioloop import tornado.web # ...
- 使用webdriverwait封装查找元素方法
对于selenium原生的查找元素方法进行封装,在timeout规定时间内循环查找页面上有没有某个元素 这样封装的好处: 1.可以有效提高查找元素的效率,避免元素还没加载完就抛异常 2.相对于time ...
- python--面向对象之三个特性:封装、继承、多态
一.面向对象简介 1.面向对象不是所有的情况都适用2.面向对象编程 a.定义类 class 类名: def 方法1(self, 参数名): 方法体 b.根据类创建对象,使用对象去执行类中的方法 obj ...
- python(函数封装)
一:Python 自定义函数 函数示意图如下: 1.使用函数的好处: 代码重用 保持一致性,易维护 可扩展性 2.函数定义 函数定义的简单规则: 函数代码块以def关键词开头 后接函数标识符名称和圆括 ...
- python中协程
在引出协成概念之前先说说python的进程和线程. 进程: 进程是正在执行程序实例.执行程序的过程中,内核会讲程序代码载入虚拟内存,为程序变量分配空间,建立 bookkeeping 数据结构,来记录与 ...
- python web的进化历程
对于所有的Web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端. 阶段1 socket服务端和客户端都自己编写 实现访问8080端口,返回一个'hello wo ...
- iOS key value coding kvc在接收json数据与 model封装中的使用
iOS key value coding kvc在接收json数据与 model封装中的使用 使用 kvc 能够极大的简化代码工作,及以后的接口维护工作: 1:先创建MovieModel类.h和 . ...
- coding++ :JS对日期的神操作封装版
格式化日期: /** * 格式化日期 * @param fmt 例如:yyyy-MM-dd 等 * @returns {*} * @constructor */ Date.prototype.Form ...
随机推荐
- 达拉草201771010105《面向对象程序设计(java)》第六周学习总结
达拉草201771010105<面向对象程序设计(java)>第六周学习总结 第一部分:理论知识 1.类.超类和子类 类继承的格式: class 新类名extends已有类名一般来说,子类 ...
- 性能测试之Mysql数据库调优
一.前言 性能调优前提:无监控不调优,对于mysql性能的监控前几天有文章提到过,有兴趣的朋友可以去看一下 二.Mysql性能指标及问题分析和定位 1.我们在监控图表中关注的性能指标大概有这么几个:C ...
- 线程状态,BLOCKED和WAITING有什么区别
线程可以通过notify,join,LockSupport.park方式进入wating状态,进入wating状态的线程等待唤醒(notify或notifyAll)才有机会获取cpu的时间片段来继续执 ...
- LLVM 中间代码归纳
Identifiers 标识符 @ 全局 % 局部 后接字符串 命名量 @name %name 无符号数字 未命名量 @42 %42 类型系统 void 空类型 <type> * 指针类型 ...
- python——字符串截取
str = ‘0123456789’ print str[0:3] #截取第一位到第三位的字符 print str[:] #截取字符串的全部字符 print str[6:] #截取第七个字符到结尾 p ...
- 数据结构 4 时间复杂度、B-树 B+树 具体应用与理解
前言 面试中,经常会问到有关于MYSQL 索引的相关概念,我们之前也都学过有关树的概念.以及二叉树.二叉查找树.红黑树等.这一节,来关注经常是数据库索引中使用的B-树 在说这些之前,我们需要了解时间复 ...
- seo搜索优化教程05-SEO常用专业术语
SEO常用的专业术语很多,星辉信息科技专门抽空进行了整理,主要如下:. SEO 根据搜索引擎规则来进行搜索引擎优化,进而使得在搜索结果中获得较好的排名 关键词 关键词也叫keywords,表示在搜索引 ...
- python http代理支持 https
首先需要2个软件来抓包. fiddler : http 代理软件可以分析,抓包,重放. wireshark : 全能抓包分析软件. RFC 提供了非常好的设计描述. https://tools.iet ...
- vue+django+webpack搭建
一.前言 最近接手了一个项目,后端是django,前端是django自带的模板,用的是jinja2,写了一段时间发现用起来特别不顺手,于是想在保持现有的模板基础上,引入vue框架,这样同事可以继续用自 ...
- search(1)- elasticsearch结构概念
上篇提到选择了elasticsearch ES作为专业化搜索引擎的核心,这篇讨论一下ES的基本结构和应用概念.首先,从硬结构方面来讲:ES是在一个集群(cluster)环境里运行的,所以ES应该具备高 ...