使用背景:

因项目使用非结构化存储,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. [BZOJ1001][BeiJing2006]狼抓兔子(最小割转最短路|平面图转对偶图)

    1001: [BeiJing2006]狼抓兔子 Time Limit: 15 Sec  Memory Limit: 162 MBSubmit: 31805  Solved: 8494[Submit][ ...

  2. 应对高并发场景的redis加锁技巧

    // 获取锁getLock() {    // 是否有正在执行的线程    boolean hasLock = false;    try {        hasLock = redisClient ...

  3. 通过JVM日志来进行安全点分析

    许多事件都可能会导致JVM暂停所有的应用线程.这类暂停又被称为”stop-the-world”(STW)暂停.触发STW暂停最常见的原因就是垃圾回收了(github中的一个例子),但不同的JIT活动( ...

  4. 笔记本电脑如何同时上内外网(通过usb外接网卡实现虚拟机连外网)

    我们这里达成的方式不是内外网切换,而是真正意义上的同时上内网和外网 原理: 通过构建虚拟机,利用usb外接网卡(某宝某东都有售,价格在50大洋左右)使虚机连接外网,然后开启虚拟机的unity模式 准备 ...

  5. TCP定时器 之 坚持定时器

    坚持定时器在接收方通告接收窗口为0,阻止发送端继续发送数据时设定. 由于连接接收端的发送窗口通告不可靠(只有数据才会确认,ACK不会确认),如果一个确认丢失了,双方就有可能因为等待对方而使连接终止:接 ...

  6. React 中 refs 的作用是什么?

    Refs 是 React 提供给我们的安全访问 DOM 元素或者某个组件实例的句柄.我们可以为元素添加 ref 属性然后在回调函数中接受该元素在 DOM 树中的句柄,该值会作为回调函数的第一个参数返回 ...

  7. 8.6培训 D1

    今天是赵和旭老师讲课(也是 zhx) 动态规划 利用最优化原理把多阶段过程转化为一系列单阶段问题,利用各阶段之间的关系,逐个求解(有点像分治?) 更具体的,假设我们可以计算出小问题的最优解,那么我们凭 ...

  8. Anaconda 配置 Python 环境

    原文地址:Anaconda 配置 Python 环境 0x00 环境 Anaconda: 2019.03 Python: 3.6.8 0x01 Linux 安装 Anaconda 交互安装 Anaco ...

  9. 配置pip镜像源(转)

    使用pip安装python扩展时,如若没有配置国内镜像源,在未翻墙的情况下,其下载速度将会特别缓慢.因此,有些时候我们必须使用国内镜像源,来解决pip下载安装速度慢的问题,比较常用的国内镜像包括: 阿 ...

  10. 【Python开发】【神经网络与深度学习】网络爬虫之python实现

    一.网络爬虫的定义 网络爬虫,即Web Spider,是一个很形象的名字. 把互联网比喻成一个蜘蛛网,那么Spider就是在网上爬来爬去的蜘蛛. 网络蜘蛛是通过网页的链接地址来寻找网页的. 从网站某一 ...