httpClient4.5.2工具类总结
使用背景:
因项目使用非结构化存储,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工具类总结的更多相关文章
- httpclient4.3 工具类
httpclient4.3 java工具类. .. .因项目须要开发了一个工具类.正经常常使用的httpclient 请求操作应该都够用了 工具类下载地址:http://download.csdn. ...
- 基于HttpClient4.5.1实现Http访问工具类
本工具类基于httpclient4.5.1实现 <dependency> <groupId>org.apache.httpcomponents</groupId> ...
- HttpClient4.5 SSL访问工具类
要从网上找一个HttpClient SSL访问工具类太难了,原因是HttpClient版本太多了,稍有差别就不能用,最后笔者干脆自己封装了一个访问HTTPS并绕过证书工具类. 主要是基于新版本Http ...
- 基于HttpClient4.5.2实现的HttpClient工具类
1.maven依赖: <dependency> <groupId>org.apache.commons</groupId> <artifactId>co ...
- java http工具类和HttpUrlConnection上传文件分析
利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式.那么就可以用任何一门语言来模拟浏览器上传文件.下面有几篇文章从http协议入手介绍了java ...
- 验证工具类 - ValidateUtils.java
验证工具类,提供验证email格式.是否ipv4.是否ipv6.是否中文.是否数字.正则表达式验证的方法. 源码如下:(点击下载 - ValidateUtils.java .commons-lang- ...
- Jsoup请求http或https返回json字符串工具类
Jsoup请求http或https返回json字符串工具类 所需要的jar包如下: jsoup-1.8.1.jar 依赖jar包如下: httpclient-4.5.4.jar; httpclient ...
- Java基础Map接口+Collections工具类
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
- Android—关于自定义对话框的工具类
开发中有很多地方会用到自定义对话框,为了避免不必要的城府代码,在此总结出一个工具类. 弹出对话框的地方很多,但是都大同小异,不同无非就是提示内容或者图片不同,下面这个类是将提示内容和图片放到了自定义函 ...
随机推荐
- 一次高IO下的GC分析之旅
一次高IO下的GC分析之旅 编码前线 关注 2018.12.21 00:06 字数 597 阅读 45评论 0喜欢 0 起因:收到GC STW报警 [监控系统]Total time for which ...
- 基于Xposed hook 实时监测微信消息
本文以微信版本6.7.3为例进行分析有hook, 大部分做微信机器人的话,首先要实时抓取微信的消息,在这里展示三种方式对微信的消息进行hook: 1.基于UI层拉取加载进行监听 2.基于微信dao层调 ...
- Golang协程实现流量统计系统(2)
从进程开始,搜索和理解进程 Google 搜索关键词: C fork example 什么是fork Fork系统调用用于创建一个称为子进程的新进程,该子进程与进行fork()调用的进程(父进程)同时 ...
- C# base64 加密解密
1.base64 to string string strPath = "aHR0cDovLzIwMy44MS4yOS40Njo1NTU3L1 9iYWlkdS9yaW5ncy9taWR ...
- php面向对象 2
继承概念:如果一个类有子类,那么该子类会继承父类的一切东西(私有成员访问不到)在定义子类的时候需要加一个关键字:extends特点:单继承,一个类只能有一个父类如果父类中有构造函数,子类在实例化的时候 ...
- [C#菜鸟]C# Hook (三) Windows常用消息大全
表A-1 Windows消息分布 消息范围 说 明 0 - WM_USER – 1 系统消息 WM_USER - 0x7FFF 自定义窗口类整数消息 WM_APP - 0xBFFF 应用程序自定义消 ...
- Android WebView使用与JavaScript使用
WebView基本使用 WebView是View的一个子类,可以让你在activity中显示网页. 可以在布局文件中写入WebView:比如下面这个写了一个填满整个屏幕的WebView: <?x ...
- Linux_ubuntu-命令系统管理
<1>查看当前日历:cal al命令用于查看当前日历,-y显示整年日历: <2>显示或设置时间:date 设置时间格式(需要管理员权限): date [MMDDhhmm[[CC ...
- Reactjs之静态路由、动态路由以及Get传值以及获取
1.新增知识点 /* react路由的配置: 1.找到官方文档 https://reacttraining.com/react-router/web/example/basic 2.安装 cnpm i ...
- apache禁止默认虚拟主机
禁止默认虚拟主机:作用使除特定域名外,其它的域名/ip无法访问此站点. 在虚拟主机配置文件中 即:/usr/local/apache2/conf/extra/httpd-vhosts.conf 将其中 ...