package com.juchn.gateway.common.utils;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import javax.net.ssl.SSLContext; import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
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.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* 新版httpClient的工具方法
*
* @author tangzl
* @since 2019年04月11日
*/
public class HttpClientUtil { static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
protected static final String CHARSET = "UTF-8";
protected static final String CHARSET_GBK = "UTF-8";
/** 默认超时时间 */
private final static int default_timeout = 10000; private static PoolingHttpClientConnectionManager cm = null; private static CloseableHttpClient httpclient = null;
static { // 多连接的线程安全的管理器
cm = new PoolingHttpClientConnectionManager();
cm.setDefaultMaxPerRoute(100); // 每个主机的最大并行链接数
cm.setMaxTotal(200); // 客户端总并行链接最大数 httpclient = HttpClients.custom().setConnectionManager(cm).build();
} /**
* 发送 get请求
*
* @param url
* @param timeout 超时时间
* @param ignoreHttps 是否忽略https证书检查
* @return
*/
public static String get(String url, Map<String, String> params, Integer timeout, boolean ignoreHttps,
HttpHost proxy) {
CloseableHttpClient client = null;
if (ignoreHttps) {
client = getIgnoreHttpsClient();
} else {
client = httpclient;
}
try {
HttpGet httpGet = null;
if (params == null)
httpGet = new HttpGet(url);
else {
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
for (Entry<String, String> entry : params.entrySet()) {
qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
String queryParams = URLEncodedUtils.format(qparams, "UTF-8");
if (url.indexOf("?") != -1) {
url += "&" + queryParams;
} else {
url += "?" + queryParams;
}
httpGet = new HttpGet(url);
}
timeout = timeout != null ? timeout : default_timeout;
RequestConfig.Builder builder = RequestConfig.custom();// 设置请求和传输超时时间
if (null != proxy) {
builder.setProxy(proxy);
}
RequestConfig requestConfig = builder.setSocketTimeout(timeout).setConnectTimeout(timeout).build();// 设置请求和传输超时时间
httpGet.setConfig(requestConfig); CloseableHttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
try {
if (entity != null)
return EntityUtils.toString(entity);
} finally {
if (entity != null)
EntityUtils.consume(entity);
response.close();
}
} catch (ParseException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (IOException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (Exception e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} finally {
/*
* try { httpclient.close(); } catch (IOException e) {
* log.error("关闭HTTP连接时出现异常:" + e); }
*/
}
return null;
} /**
* 发送 get请求
*
* @param url
* @param timeout 超时时间
* @param ignoreHttps 是否忽略https证书检查
* @return
*/
public static String get(String url, Map<String, String> params, Map<String, Object> headers, Integer timeout,
boolean ignoreHttps) {
CloseableHttpClient client = null;
if (ignoreHttps) {
client = getIgnoreHttpsClient();
} else {
client = httpclient;
}
try {
HttpGet httpGet = null;
if (params != null && params.size() > 0) {
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
for (Entry<String, String> entry : params.entrySet()) {
qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
String queryParams = URLEncodedUtils.format(qparams, "UTF-8");
if (url.indexOf("?") != -1) {
url += "&" + queryParams;
} else {
url += "?" + queryParams;
} }
httpGet = new HttpGet(url);
httpGet.setHeader("Content-type", "application/json;charset=UTF-8");
if (headers != null && headers.size() > 0) {
for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
String key = iter.next();
httpGet.setHeader(key, headers.get(key).toString());
}
} timeout = timeout != null ? timeout : default_timeout;
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
.build();// 设置请求和传输超时时间
httpGet.setConfig(requestConfig); CloseableHttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
try {
if (entity != null)
return EntityUtils.toString(entity);
} finally {
if (entity != null)
EntityUtils.consume(entity);
response.close();
}
} catch (ParseException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (IOException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (Exception e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} finally {
/*
* try { httpclient.close(); } catch (IOException e) {
* log.error("关闭HTTP连接时出现异常:" + e); }
*/
}
return null;
} /**
* 发送 get请求
*
* @param url
* @param timeout 超时时间
* @param ignoreHttps 是否忽略https证书检查
* @return
*/
public static String get(String url, Map<String, String> params, Integer timeout, boolean ignoreHttps) {
CloseableHttpClient client = null;
if (ignoreHttps) {
client = getIgnoreHttpsClient();
} else {
client = httpclient;
}
try {
HttpGet httpGet = null;
if (params == null)
httpGet = new HttpGet(url);
else {
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
for (Entry<String, String> entry : params.entrySet()) {
qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
String queryParams = URLEncodedUtils.format(qparams, "UTF-8");
if (url.indexOf("?") != -1) {
url += "&" + queryParams;
} else {
url += "?" + queryParams;
}
httpGet = new HttpGet(url);
}
timeout = timeout != null ? timeout : default_timeout;
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
.build();// 设置请求和传输超时时间
httpGet.setConfig(requestConfig); CloseableHttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
try {
if (entity != null)
return EntityUtils.toString(entity);
} finally {
if (entity != null)
EntityUtils.consume(entity);
response.close();
}
} catch (ParseException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (IOException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (Exception e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} finally {
/*
* try { httpclient.close(); } catch (IOException e) {
* log.error("关闭HTTP连接时出现异常:" + e); }
*/
}
return null;
} /**
* 发送get请求
*
* @param url
* @param timeout 超时时间(毫秒)
* @return
*/
public static String get(String url, Map<String, String> params, Integer timeout) {
return get(url, params, timeout, false);
} /**
* 发送get请求
*
* @param url
* @param timeout 超时时间(毫秒)
* @return
*/
public static String get(String url, Map<String, String> params, Map<String, Object> headers) {
return get(url, params, headers, null, false);
} /**
* 发送 get请求
*
* @param url
* @param timeout 超时时间
* @param ignoreHttps 是否忽略https证书检查
* @return
*/
public static String get(String url, Integer timeout, boolean ignoreHttps) {
return get(url, null, timeout, ignoreHttps);
} /**
* 获取忽略https证书的client
*
* @return
*/
public static CloseableHttpClient getIgnoreHttpsClient() {
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} return HttpClients.custom().setSslcontext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
} /**
* 发送 post请求
*
* @param url
* @param timeout 超时时间(毫秒)
* @param params 请求参数
* @return
*/
public static String post(String url, Map<String, String> params, Integer timeout) { CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
try { HttpPost httpPost = new HttpPost(url);
if (params != null) {
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
for (Entry<String, String> entry : params.entrySet()) {
qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(qparams, "UTF-8"));
}
timeout = timeout != null ? timeout : default_timeout;
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
.build();// 设置请求和传输超时时间
httpPost.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
try {
if (entity != null) {
StringBuilder sb = new StringBuilder();
String line = null;
InputStream inputStream = entity.getContent();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} finally {
inputStream.close();
}
return sb.toString();
}
} finally {
response.close();
} /*
* try { if (entity != null) return EntityUtils.toString(entity); } finally { if
* (entity != null) EntityUtils.consume(entity); response.close(); }
*/
} catch (ParseException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (IOException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (Exception e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} finally {
/*
* try { httpclient.close(); } catch (IOException e) {
* log.error("关闭HTTP连接时出现异常:" + e); }
*/
}
return null;
} /**
* 发送 post请求 带请求头
*
* @param url
* @param params
* @param headers
* @param timeout
* @return
*/
public static String post(String url, Map<String, String> params, Map<String, String> headers, Integer timeout) { CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
try {
HttpPost httpPost = new HttpPost(url); if (params != null) {
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
for (Entry<String, String> entry : params.entrySet()) {
qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(qparams, CHARSET));
}
if (headers != null && headers.size() > 0) {
for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
String key = iter.next();
httpPost.setHeader(key, headers.get(key));
}
}
timeout = timeout != null ? timeout : default_timeout;
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
.build();// 设置请求和传输超时时间
httpPost.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity(); // 方法一:
try {
if (entity != null) {
StringBuilder sb = new StringBuilder();
String line = null;
InputStream inputStream = entity.getContent();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} finally {
inputStream.close();
}
return sb.toString();
}
} finally {
response.close();
} // 方法二:
/*
* try { if (entity != null) return EntityUtils.toString(entity); } finally { if
* (entity != null) EntityUtils.consume(entity); response.close(); }
*/
} catch (ParseException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (IOException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (Exception e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} finally {
/*
* try { httpclient.close(); } catch (IOException e) {
* log.error("关闭HTTP连接时出现异常:" + e); }
*/
}
return null;
} /**
* post body
*
* @param url
* @param params 请求body内容
* @return
*/
public static String postBody(String url, String params, Map<String, String> headers, Integer timeout) { CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
try { HttpPost httpPost = new HttpPost(url);
if (!StringUtils.isEmpty(params)) {
httpPost.setEntity(new StringEntity(params, "UTF-8"));
}
if (headers != null && headers.size() > 0) {
for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
String key = iter.next();
httpPost.setHeader(key, headers.get(key));
}
}
timeout = timeout != null ? timeout : default_timeout;
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
.build();// 设置请求和传输超时时间
httpPost.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
// 方法一:
try {
if (entity != null) {
StringBuilder sb = new StringBuilder();
String line = null;
InputStream inputStream = entity.getContent();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} finally {
inputStream.close();
}
return sb.toString();
}
} finally {
response.close();
}
// 方法二:
/*
* try { if (entity != null) return EntityUtils.toString(entity); } finally { if
* (entity != null) EntityUtils.consume(entity); response.close(); }
*/
} catch (ParseException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (IOException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (Exception e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} finally {
}
return null;
} public static String postBodyJson(String url, String params, Map<String, String> headers, Integer timeout) { CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
try { HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
if (!StringUtils.isEmpty(params)) {
httpPost.setEntity(new StringEntity(params, "UTF-8"));
}
if (headers != null && headers.size() > 0) {
for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
String key = iter.next();
httpPost.setHeader(key, headers.get(key));
}
}
timeout = timeout != null ? timeout : default_timeout;
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
.build();// 设置请求和传输超时时间
httpPost.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
// 方法一:
try {
if (entity != null) {
StringBuilder sb = new StringBuilder();
String line = null;
InputStream inputStream = entity.getContent();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} finally {
inputStream.close();
}
return sb.toString();
}
} finally {
response.close();
}
// 方法二:
/*
* try { if (entity != null) return EntityUtils.toString(entity); } finally { if
* (entity != null) EntityUtils.consume(entity); response.close(); }
*/
} catch (ParseException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (IOException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (Exception e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} finally {
}
return null;
} public static String putBodyJson(String url, String params, Map<String, String> headers, Integer timeout) { CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
try { HttpPut httpPost = new HttpPut(url);
httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
if (!StringUtils.isEmpty(params)) {
httpPost.setEntity(new StringEntity(params, "UTF-8"));
}
if (headers != null && headers.size() > 0) {
for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
String key = iter.next();
httpPost.setHeader(key, headers.get(key));
}
}
timeout = timeout != null ? timeout : default_timeout;
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
.build();// 设置请求和传输超时时间
httpPost.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
// 方法一:
try {
if (entity != null) {
StringBuilder sb = new StringBuilder();
String line = null;
InputStream inputStream = entity.getContent();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} finally {
inputStream.close();
}
return sb.toString();
}
} finally {
response.close();
}
// 方法二:
/*
* try { if (entity != null) return EntityUtils.toString(entity); } finally { if
* (entity != null) EntityUtils.consume(entity); response.close(); }
*/
} catch (ParseException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (IOException e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} catch (Exception e) {
log.error("发送HTTP请求时出现异常:" + e);
e.printStackTrace(System.out);
} finally {
}
return null;
}
}

httpClinent工具类的更多相关文章

  1. Java基础Map接口+Collections工具类

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  2. Android—关于自定义对话框的工具类

    开发中有很多地方会用到自定义对话框,为了避免不必要的城府代码,在此总结出一个工具类. 弹出对话框的地方很多,但是都大同小异,不同无非就是提示内容或者图片不同,下面这个类是将提示内容和图片放到了自定义函 ...

  3. [转]Java常用工具类集合

    转自:http://blog.csdn.net/justdb/article/details/8653166 数据库连接工具类——仅仅获得连接对象 ConnDB.java package com.ut ...

  4. js常用工具类.

    一些js的工具类 复制代码 /** * Created by sevennight on 15-1-31. * js常用工具类 */ /** * 方法作用:[格式化时间] * 使用方法 * 示例: * ...

  5. Guava库介绍之实用工具类

    作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...

  6. Java程序员的日常—— Arrays工具类的使用

    这个类在日常的开发中,还是非常常用的.今天就总结一下Arrays工具类的常用方法.最常用的就是asList,sort,toStream,equals,copyOf了.另外可以深入学习下Arrays的排 ...

  7. .net使用正则表达式校验、匹配字符工具类

    开发程序离不开数据的校验,这里整理了一些数据的校验.匹配的方法: /// <summary> /// 字符(串)验证.匹配工具类 /// </summary> public c ...

  8. WebUtils-网络请求工具类

    网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

  9. JAVA 日期格式工具类DateUtil.java

    DateUtil.java package pers.kangxu.datautils.utils; import java.text.SimpleDateFormat; import java.ut ...

随机推荐

  1. Oracle 调试存储过程

    调试过程对找到一个存过的bug或错误是非常重要的,Oracle作为一款强大的商业数据库,其上面的存过少则10几行,多则上千行,免不了bug的存在,存过上千行的话,找bug也很费力,通过调试可以大大减轻 ...

  2. Oracle创建索引;查询索引

    1.创建索引 create index 索引名 on 表名(列名); 2.删除索引 drop index 索引名; 3.创建组合索引 create index 索引名 on 表名(列名1,,列名2); ...

  3. Java秒杀实战 (七)安全优化

    转自:https://blog.csdn.net/qq_41305266/article/details/81174782 一.隐藏秒杀地址 思路:秒杀开始前,先去请求接口获取秒杀地址 1.接口改造, ...

  4. 使用pycharm 编写代码 并在远程主机上运行

    一 要求 远程主机有python解释器 二 在菜单栏,File -> Settings… -> Project ×× -> Project Interpreter,点击右侧 Add按 ...

  5. paypal支付 NVP支付 paypal 手续费 GetTransactionDetails

    主要内容: 本文章主要讲解的是NVP的对接,以最简单的接口案例,讲解一下对接NVP的方案. 先提供下paypal 官方文档的主要功能对接说明,如下 1.请求API 服务器端点 描述 https://a ...

  6. C++中volatile

    volatile只保证其“可见性”,不保证其“原子性”. 执行count++;这条语句由3条指令组成: (1)将 count 的值从内存加载到 cpu 的某个 寄存器r: (2)将 寄存器r 的值 + ...

  7. Image Processing and Computer Vision_Review:Local Invariant Feature Detectors: A Survey——2007.11

    翻译 局部不变特征探测器:一项调查 摘要 -在本次调查中,我们概述了不变兴趣点探测器,它们如何随着时间的推移而发展,它们如何工作,以及它们各自的优点和缺点.我们首先定义理想局部特征检测器的属性.接下来 ...

  8. 寻找一组数中最大的K个数

    对于"从一组数中挑出最大的K个数"这个在面试中经常会遇到,所以这次好好的去解析它,而当拿到这个问题时第一时间能想到解法就是:先对数据进行排序,然后再取最大的K个元素,当然这思路没毛 ...

  9. wiki页面文本挖掘

    import os,sysimport sysfrom bs4 import BeautifulSoupimport urllib.request# reload(sys)# sys.setdefau ...

  10. 对List<Map>里的map的某个属性重复的值进行处理的方法

    package test; import java.util.*;import java.util.stream.Collectors; public class Test5 { public sta ...