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. Newtonsoft.Json基本用法

    1.将一个 Object 序列化成 JSON: DataSet detail = sqlDB.GetDataSet(string.Format("select * from student ...

  2. Java获取近7个月的起止时间

    话不多说,直接上代码 public class Test { @org.junit.Test public void tets() { SimpleDateFormat format = new Si ...

  3. JS的一些简单基础运算题

    1.输入一个四位数,在控制台分别显示个位,十位,百位,千位的数值 var a = prompt("请输入一个四位数的正整数"); var b = parseInt(a/1000); ...

  4. vsCode设置代码片段

    输入vue.json { "Print to console": { "prefix": "vv", "body": [ ...

  5. json树迭代

    getArray(data){ for (var i in data) { if(data[i].disabled){ data[i].disabled = false } if(data[i].ch ...

  6. Spring7大模块

    Spring 框架是一个分层架构,由 7 个定义良好的模块组成.Spring 模块构建在核心容器之上,核心容器定义了创建.配置和管理 bean 的方式,组成 Spring 框架的每个模块(或组件)都可 ...

  7. Emeditor代码编辑器常见的正则表达式总结

    Emeditor 目前来说是我个人感觉非常不错的一款记事本软件, 其中查找替换功能由于支持正则表达式而显得非常强大. <tr[^>]*> 匹配:<tr xxxxxxxxxxxx ...

  8. mORMot学习笔记2-2种方式查询数据

    本例使用SqlServer 第一种方式结果放入Memo控件,,需要引用SynCommons, SynDB, SynOleDb; procedure TForm1.Button1Click(Sender ...

  9. JavaScript 的基本使用

    JavaScript 基本语法要求: 1.JS的写法是严格区分大小写的. 2.标识符的起名要求跟java的是一样的,第一个位置可以说字母.下划线.美元符号.其他位置可以字母.下划线.美元符号.数字. ...

  10. fnmatch:Unix式glob模式匹配,简单场景下可以代替正则

    介绍 fnmatch模块用于根据glob模式(如Unix shell所使用的的模式)比较文件名 简单匹配 import fnmatch ''' fnmatch将一个文件名与一个模式进行比较,并返回一个 ...