使用背景:

因项目使用非结构化存储,http相关jar包统一升级到httpClient4.5.2,查阅相关文档总结如下,以咨分享,望不吝指教。

依赖jar包

httpclient-4.5.2.jar、httpcore-4.4.4.jar、sl4j.jar

HttpClientUtil.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
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.HashMap;
import java.util.List;
import java.util.Map; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
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.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* 参考:https://www.cnblogs.com/luken2017/p/6386055.html
* https://www.2cto.com/net/201709/681448.html
* https://www.cnblogs.com/likaitai/p/5431246.html
*/
public class HttpClientUtil { private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class); /** 连接池 */
private static PoolingHttpClientConnectionManager connManager = null; // 代理信息
private static final String PROXY_IP = "10.5.3.9";
private static final int PROXY_PORT = 80; private static int maxTotalPool = 1000;
private static int maxConPerRoute = 20;
private static int allTimeout = 15000; private static HashMap<String, HttpClientUtil> map = new HashMap<>(); private static Object object = new Object(); private String url = null; private CloseableHttpClient httpClient = null; public static HttpClientUtil getInstance(String strUrl) {
HttpClientUtil instance = null;
if ((instance = map.get(strUrl)) == null) {
synchronized (object) {
initConnManager(); instance = new HttpClientUtil();
instance.httpClient = getHttpClient(false, allTimeout);
instance.url = strUrl;
map.put(strUrl, instance);
}
}
return instance;
} public static HttpClientUtil getProxyInstance(String strUrl) {
HttpClientUtil instance = null;
if ((instance = map.get(strUrl)) == null) {
synchronized (object) {
initConnManager(); instance = new HttpClientUtil();
instance.httpClient = getHttpClient(true, allTimeout);
instance.url = strUrl;
map.put(strUrl, instance);
}
}
return instance;
} public static void initConnManager() {
if (connManager == null) {
// 创建ssl安全访问连接
// 获取创建ssl上下文对象
try {
SSLContext sslContext = getSSLContext(true, null, null);
// 注册
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext)).build();
// ssl注册到连接池
connManager = new PoolingHttpClientConnectionManager(registry);
connManager.setMaxTotal(maxTotalPool); // 连接池最大连接数
connManager.setDefaultMaxPerRoute(maxConPerRoute); // 每个路由最大连接数 } catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
} private static SSLContext getSSLContext(boolean isDeceive, File creFile, String crePwd)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException,
IOException {
SSLContext sslContext = null; if (isDeceive) {
sslContext = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager x509TrustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// Do nothing
} @Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// Do nothing
} @Override
public X509Certificate[] getAcceptedIssuers() {
// Do nothing
return new X509Certificate[0];
}
};
sslContext.init(null, new TrustManager[] { x509TrustManager }, null);
} else {
if (null != creFile && creFile.length() > 0) {
if (null != crePwd) {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(creFile), crePwd.toCharArray());
sslContext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy())
.build();
} else {
throw new SSLHandshakeException("整数密码为空");
}
}
} return sslContext;
} public static CloseableHttpClient getHttpClient(boolean startProxy, int timeout) {
return getHttpClient(startProxy, timeout, timeout, timeout);
} private static CloseableHttpClient getHttpClient(boolean startProxy, int connectionRquestTimeout, int connectTimeout, int socketTimeout) {
// 配置请求参数
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(connectionRquestTimeout)
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.build(); // 配置超时回调机制
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() { @Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount >= 3) {// 如果已经重试了3次,就放弃
return false;
}
if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
return true;
}
if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
return false;
}
if (exception instanceof InterruptedIOException) {// 超时
return true;
}
if (exception instanceof UnknownHostException) {// 目标服务器不可达
return false;
}
if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
return false;
}
if (exception instanceof SSLException) {// ssl握手异常
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
// 如果请求是幂等的,就再次尝试
return !(request instanceof HttpEntityEnclosingRequest) ? true : false;
} }; HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setConnectionManager(connManager).setDefaultRequestConfig(requestConfig)
.setRetryHandler(retryHandler); if (startProxy) {
HttpHost proxy = new HttpHost(PROXY_IP, PROXY_PORT);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
httpClientBuilder.setRoutePlanner(routePlanner);
} return httpClientBuilder.build();
} public String postJson(String json) {
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
post.setEntity(entity);
String responseContent = null;
CloseableHttpResponse response = null;
try {
response = httpClient.execute(post);
int status = response.getStatusLine().getStatusCode();
printStatus(status);
if (status == HttpStatus.SC_OK) {
responseContent = EntityUtils.toString(response.getEntity(), Consts.UTF_8.name());
} } catch (IOException e) {
LOG.error(e.getMessage(), e);
} finally {
post.abort();
post.releaseConnection();
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
response.close();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
}
}
return responseContent;
} /**
* 发送 GET 请求(HTTP),不带输入数据
*
* @param url
* @return
*/
public String doGet(String url) {
return doGet(new HashMap<String, Object>());
} /**
* 发送 GET 请求(HTTP),K-V形式
*
* @param url
* @param params
* @return
*/
public String doGet(Map<String, Object> params) {
String apiUrl = url;
StringBuilder param = new StringBuilder();
int i = 0;
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (i == 0) {
param.append("?");
} else {
param.append("&");
}
param.append(entry.getKey()).append("=").append(entry.getValue());
i++;
} apiUrl += param;
String result = null;
CloseableHttpResponse response = null;
HttpGet httpGet = null;
try {
httpGet = new HttpGet(apiUrl);
response = httpClient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
printStatus(status);
if (status == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(response.getEntity(), Consts.UTF_8.name());
}
}
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} finally {
httpGet.abort();
httpGet.releaseConnection();
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
response.close();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
}
} return result;
} /**
* 发送 POST 请求(HTTP),K-V形式
*
* @param url
* 接口URL
* @param params
* 参数map
* @return
*/
public String doPost(Map<String, String> params) {
String result = null;
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
try {
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Consts.UTF_8.name()));
response = httpClient.execute(httpPost);
int status = response.getStatusLine().getStatusCode();
printStatus(status);
if (status == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(response.getEntity(), Consts.UTF_8.name());
}
} } catch (IOException e) {
LOG.error(e.getMessage(), e);
} finally {
httpPost.abort();
httpPost.releaseConnection();
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
response.close();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
}
}
return result;
} private void printStatus(int status) {
LOG.info("返回状态:{}", status);
}
}

httpClient4.5.2工具类总结的更多相关文章

  1. httpclient4.3 工具类

    httpclient4.3  java工具类. .. .因项目须要开发了一个工具类.正经常常使用的httpclient 请求操作应该都够用了 工具类下载地址:http://download.csdn. ...

  2. 基于HttpClient4.5.1实现Http访问工具类

    本工具类基于httpclient4.5.1实现 <dependency> <groupId>org.apache.httpcomponents</groupId> ...

  3. HttpClient4.5 SSL访问工具类

    要从网上找一个HttpClient SSL访问工具类太难了,原因是HttpClient版本太多了,稍有差别就不能用,最后笔者干脆自己封装了一个访问HTTPS并绕过证书工具类. 主要是基于新版本Http ...

  4. 基于HttpClient4.5.2实现的HttpClient工具类

    1.maven依赖: <dependency> <groupId>org.apache.commons</groupId> <artifactId>co ...

  5. java http工具类和HttpUrlConnection上传文件分析

    利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式.那么就可以用任何一门语言来模拟浏览器上传文件.下面有几篇文章从http协议入手介绍了java ...

  6. 验证工具类 - ValidateUtils.java

    验证工具类,提供验证email格式.是否ipv4.是否ipv6.是否中文.是否数字.正则表达式验证的方法. 源码如下:(点击下载 - ValidateUtils.java .commons-lang- ...

  7. Jsoup请求http或https返回json字符串工具类

    Jsoup请求http或https返回json字符串工具类 所需要的jar包如下: jsoup-1.8.1.jar 依赖jar包如下: httpclient-4.5.4.jar; httpclient ...

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

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

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

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

随机推荐

  1. Java并发编程的艺术笔记(六)——HashMap、ConcurentHashMap的原理与实现

    一.线程不安全的HashMap 多线程环境下,使用HashMap进行put操作会引起死循环(jdk1.7 Entry链表形成环形数据结构),导致CPU利用率接近100%. 结构:数组 table[]+ ...

  2. 前端MVC、MVVM的简单实现

    MVC MVC是一种设计模式,它将应用划分为3个部分:数据(模型).展示层(视图)和用户交互层.结合一下下图,更能理解三者之间的关系.换句话说,一个事件的发生是这样的过程 用户和应用交互 控制器的事件 ...

  3. 如何使用IDEA运行 一个分布式的项目

    前一段时间,曾不止一次的尝试过,如何把一个分布式的maven项目,用IDE运行起来.连续的几次失败,让我明白之前启动的方式是有问题的.因此把正确的启动方式整理了一下 .引以为戒 一.起初启动失败的原因 ...

  4. 第十四周课程总结 & 实验报告

    一.JDBC JDBC概述 JDBC提供了一种与平台无关的用于执行SQL语句的标准JavaAPI,可以方便的实现多种关系型数据库的统一操作,它由一组用Java语言编写的类和接口组成 JDBC的主要操作 ...

  5. 190707Python-RabbitMQ

    一.简单的RabbitMQ示例 生产者 # Author:Li Dongfei import pika connection = pika.BlockingConnection( pika.Conne ...

  6. Python学习笔记:字典型的数据结构

    根据书上的定义,字典是将数据与键相关联,这个键相当于是一组数据的一个名称,键必须是唯一的. python中提供了内置的映射类型--字典.映射其实就是一组key和value以及之间的映射函数,其特点是: ...

  7. spark 笔记 5: SparkContext,SparkConf

    SparkContext 是spark的程序入口,相当于熟悉的'main'函数.它负责链接spark集群.创建RDD.创建累加计数器.创建广播变量. ) scheduler.initialize(ba ...

  8. 浏览器端-W3School-HTML:HTML DOM Table 对象

    ylbtech-浏览器端-W3School-HTML:HTML DOM Table 对象 1.返回顶部 1. HTML DOM Table 对象 Table 对象 Table 对象代表一个 HTML ...

  9. 阶段3 2.Spring_02.程序间耦合_1 编写jdbc的工程代码用于分析程序的耦合

    创建新项目.不选择骨架 打包方式选择是jar 增加mysql的包依赖 创建demo类来讲解程序的耦合 原来里面提供了sql语句.拿到mysql没执行

  10. python__007内置函数

    本文摘自:https://docs.python.org/3/library/functions.html?highlight=built#ascii     内置功能     abs() delat ...