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. css 对div用hover设置border,出现抖动和div走位问题,解决方法

    样式设置 : div:hover { border:1px solid red;} 当鼠标移动到div时,产生抖动和偏移. 产生的原因: 是因为设置border时设置了1px边框,多出的这1px,与其 ...

  2. 解决设置了display:none的元素,会先展示再隐藏

    问题:元素明明设置了display:none,但是在刷新页面的时候却会先显示了出来,然后才会隐藏,实现display:none 原因:由于元素渲染的时候,样式还没有应用上去,导致的 解决办法:使用内联 ...

  3. docker第二篇 Docker基础用法

    Docker中的容器 lxc -> libcontainer -> runC OCI (Open Container Initiative) 由Linux基金会主导于2015年6月创立 作 ...

  4. MongoDB——理论及使用命令详解 数据库

    数据存储阶段 文件管理阶段(.txt  .doc .xls) 优点: 1 使用简单,展现直观 2 可以长期保存数据 3 可存储数据量比较大 缺点: 1 查找不方便, 2 容易造成数据冗余, 3 格式不 ...

  5. oracle ORA-16038 ORA-00257

    出现 ORA-16038时也可以参考下边的错误,好像有关联影响 出现ORA-00257错误(空间不足错误),通过查找资料,绝大部分说这是由于归档日志太多,占用了全部的硬盘剩余空间导致的,通过简单删除日 ...

  6. Math.pow

    一个Math函数,例如:Math.pow(4,3);返回4的三次幂,用法:Math.pow(x,y) x 必需传.底数.必须是数字. y 必需传.幂数.必须是数字. 如果结果是虚数或负数,则该方法将返 ...

  7. vue项目环境的搭建

    首先要明白Vue是基于node的,在公司要使用vue来开发项目的话肯定是要先安装node的,下面是搭建一个最简单的vue项目环境 一 安装node 这个可以去node的官网下载对应版本 安装好之后 c ...

  8. PHP常见设计模式

    简单工厂 <?php # 简单工厂 abstract class mycoach { public function __construct(){} } class cultivatecpc e ...

  9. Spring bean 实现InitializingBean和DisposableBean接口实现初始化和销毁前操作

    # InitializingBean接口> Spring Bean 实现这个接口,重写afterPropertiesSet方法,这样spring初始化完这个实体类后会调用这个方法```@Over ...

  10. SVN - Subversion

    Subversion yum install -y subversion 或者 subversion Edge 下载: # wget https://downloads-guests.open.col ...