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. TypeScript入门五:TypeScript的接口

    TypeScript接口的基本使用 TypeScript函数类型接口 TypeScript可索引类型接口 TypeScript类类型接口 TypeScript接口与继承 一.TypeScript接口的 ...

  2. python中的not的意思

    python中的not的意思 在python中,not是逻辑判断,用于布尔值true和false,not true是false,not false是true.以下是not的一些常见用法:(1)当表达式 ...

  3. vue学习(8)-过渡transition&动画animate

      进入之前                                                    离开之后 v-enter---v-enter-to            v-lea ...

  4. requests模块高级操作之proxies

    一.代理proxy 概念:代理服务器 作用:请求和响应的转发 免费代理 www.goubanjia.com 快代理 西祠代理 代理精灵(付费) 匿名度: 透明:对方服务器知道你使用代理也知道你真实ip ...

  5. 如何部署struts开发环境

    1 首先登陆http://archive.apache.org/dist/struts/source/页面,会看到struts的下载页面 2 下载struts的最新版本struts2-2.2.1-sr ...

  6. asp.net 简单的身份验证

    1 通常我们希望已经通过身份验证的才能够登录到网站的后台管理界面,对于asp.net 介绍一种简单的身份验证方式 首先在webconfig文件中添加如下的代码 <!--身份验证--> &l ...

  7. ASR性能测试方案--详细见云盘

    目录: 1. 什么是WER 2. WER计算原理 3. WER测试设计方案 4. 当前业界识别水平 1. 什么是WER 在语音识别(Automatic Speech Recognition, ASR) ...

  8. 【Struts2】Ognl与ValueStack

    一.OGNL 1.1 概述 1.2 OGNL 五大类功能 1.3 演示 二.ValueStack 2.1 概述 2.2 ValueStack结构 2.3 结论 2.3 一些问题 三.OGNL表达式常见 ...

  9. shell脚本编程进阶及RAID和LVM应用2

    文件测试 存在性测试 -a FILE 这个选项的效果与-e 相同.但是它已经被弃用了,并且不鼓励使用 -e FILE 文件的存在性测试,存在则为真,否则为假 例:~]# [ -e /etc/rc.d/ ...

  10. Java&Selenium 鼠标键盘及滚动条控制相关方法封装

    一.摘要 本片博文主要展示在使用Selenium with java做web自动化时,一些不得不模拟鼠标操作.模拟键盘操作和控制滚动条的java代码 二.模拟鼠标操作 package util; im ...