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 ...
随机推荐
- Vue的fetch的概述和使用
Fetch基本概念 (前端小白,刚学习vue,写的不好或是不对,请各位大佬多多指正!感激不尽!) Fetch 是一个现代的概念, 等同于 XMLHttpRequest.它提供了许多与XMLHttpRe ...
- Canvas 使用及应用
Canvas canvas 是 HTML5 当中我最喜欢的所有新特性中我最喜欢的一个标签了.因为它太强大了,各种有意思的特效都可以实现. 1. canvas 的基本使用方法 - 它是一个行内块元素 - ...
- Slog27_支配vue框架初阶项目之博客网站-样式居中
ArthurSlog SLog-27 Year·1 Guangzhou·China July 30th 2018 GitHub 掘金主页 简书主页 segmentfault 没有写够足够的代码量,想成 ...
- JAVA Integer值的范围
原文出处:http://hi.baidu.com/eduask%C9%BD%C8%AA/blog/item/227bf4d81c71ebf538012f53.html package com.test ...
- 【从零单排HBase 01】从一无所知到5分钟快速了解HBase
最近公司正好准备投入HBase,因此做了一些基础学习准备,所以先暂时停止MySQL的更新,把HBase的学习心得跟大家分享一下,接下来一段时间都会发布HBase相关内容. 在学的过程中,发现跟MySQ ...
- 关于nw的简单应用
最近使用到了桌面开发应用nw.js.进行简单的介绍一下,基本用法 nwjs实际上是基于node js的,支持node js的所有api 中文官网https://nwjs.org.cn/ 第一步.在官网 ...
- vs远程调试iis
1.在开发电脑上 找到 D:\Software\VS2010\Common7\IDE\Remote Debugger 下面msvsmon.exe所在的两个文件夹x86和x64,使用x86或者x64是根 ...
- wentiqingdan
1. Python不用在行尾加分号,也不要用分号将两条命令放在同一行,但加上分号也能执行,不像C/C++分号是必须加的,缺了就会出错. 2. C属于编译型语言,Python属解型语言 编译型的优点是& ...
- JavaFX之多个FXML加载和通信
前言 在使用了FXML设计布局后,新的问题随之而来,当一个程序需要多个界面时,我们不可能在一个FXML中写出全部布局,这样太过于臃肿不易查看和维护(当然非要这么做也是可以的),这里就涉及到如何在一个F ...
- P5596 【XR-4】题 笔记
P5596 [XR-4]题 其实这题我昨天没做出来--所以今天写一下笔记 昨天我还信誓旦旦地说这一定是一道黑题\(OTZ\).果然菜是原罪. 另外吐槽一下科技楼机房频繁停电,昨天写了两小时的树刨和倍增 ...