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

时间:2022-06-22 05:07:23

1.maven依赖:

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
>

2.HttpClientUtil工具类

import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Map.Entry; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException; import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; /**
*
* @author Qian Wenjin
*
*/
public class HttpClientUtil { private static final Logger LOG = LogManager.getLogger(HttpClientUtil.class); private static final int CONNECT_TIMEOUT = 5000;//设置超时毫秒数 private static final int SOCKET_TIMEOUT = 10000;//设置传输毫秒数 private static final int REQUESTCONNECT_TIMEOUT = 3000;//获取请求超时毫秒数 private static final int CONNECT_TOTAL = 200;//最大连接数 private static final int CONNECT_ROUTE = 20;//设置每个路由的基础连接数 private static final int VALIDATE_TIME = 30000;//设置重用连接时间 private static final String RESPONSE_CONTENT = "通信失败"; private static PoolingHttpClientConnectionManager manager = null; private static CloseableHttpClient client = null; static {
ConnectionSocketFactory csf = PlainConnectionSocketFactory.getSocketFactory();
LayeredConnectionSocketFactory lsf = createSSLConnSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", csf).register("https", lsf).build();
manager = new PoolingHttpClientConnectionManager(registry);
manager.setMaxTotal(CONNECT_TOTAL);
manager.setDefaultMaxPerRoute(CONNECT_ROUTE);
manager.setValidateAfterInactivity(VALIDATE_TIME);
SocketConfig config = SocketConfig.custom().setSoTimeout(SOCKET_TIMEOUT).build();
manager.setDefaultSocketConfig(config);
RequestConfig requestConf = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
.setConnectionRequestTimeout(REQUESTCONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
client = HttpClients.custom().setConnectionManager(manager).setDefaultRequestConfig(requestConf).setRetryHandler(
//实现了HttpRequestRetryHandler接口的
//public boolean retryRequest(IOException exception, int executionCount, HttpContext context)方法
(exception, executionCount, context) -> {
if(executionCount >= 3)
return false;
if(exception instanceof NoHttpResponseException)//如果服务器断掉了连接那么重试
return true;
if(exception instanceof SSLHandshakeException)//不重试握手异常
return false;
if(exception instanceof InterruptedIOException)//IO传输中断重试
return true;
if(exception instanceof UnknownHostException)//未知服务器
return false;
if(exception instanceof ConnectTimeoutException)//超时就重试
return true;
if(exception instanceof SSLException)
return false; HttpClientContext cliContext = HttpClientContext.adapt(context);
HttpRequest request = cliContext.getRequest();
if(!(request instanceof HttpEntityEnclosingRequest))
return true;
return false;
}).build();
if(manager!=null && manager.getTotalStats()!=null)
LOG.info("客户池状态:"+manager.getTotalStats().toString());
} private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
SSLContext context;
try {
context = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
sslsf = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
} catch (NoSuchAlgorithmException e) {
LOG.error("SSL上下文创建失败,由于" + e.getLocalizedMessage());
e.printStackTrace();
}
return sslsf;
} private String res(HttpRequestBase method) {
HttpClientContext context = HttpClientContext.create();
CloseableHttpResponse response = null;
String content = RESPONSE_CONTENT;
try {
response = client.execute(method, context);//执行GET/POST请求
HttpEntity entity = response.getEntity();//获取响应实体
if(entity!=null) {
Charset charset = ContentType.getOrDefault(entity).getCharset();
content = EntityUtils.toString(entity, charset);
EntityUtils.consume(entity);
}
} catch(ConnectTimeoutException cte) {
LOG.error("请求连接超时,由于 " + cte.getLocalizedMessage());
cte.printStackTrace();
} catch(SocketTimeoutException ste) {
LOG.error("请求通信超时,由于 " + ste.getLocalizedMessage());
ste.printStackTrace();
} catch(ClientProtocolException cpe) {
LOG.error("协议错误(比如构造HttpGet对象时传入协议不对(将'http'写成'htp')or响应内容不符合),由于 " + cpe.getLocalizedMessage());
cpe.printStackTrace();
} catch(IOException ie) {
LOG.error("实体转换异常或者网络异常, 由于 " + ie.getLocalizedMessage());
ie.printStackTrace();
} finally {
try {
if(response!=null) {
response.close();
} } catch(IOException e) {
LOG.error("响应关闭异常, 由于 " + e.getLocalizedMessage());
} if(method!=null) {
method.releaseConnection();
} } return content;
} public String get(String url) {
HttpGet get = new HttpGet(url);
return res(get);
} public String get(String url, String cookie) {
HttpGet get = new HttpGet(url);
if(StringUtils.isNotBlank(cookie))
get.addHeader("cookie", cookie);
return res(get);
} public byte[] getAsByte(String url) {
return get(url).getBytes();
} public String getHeaders(String url, String cookie, String headerName) {
HttpGet get = new HttpGet(url);
if(StringUtils.isNotBlank(cookie))
get.addHeader("cookie", cookie);
res(get);
Header[] headers = get.getHeaders(headerName);
return headers == null ? null : headers.toString();
} public String getWithRealHeader(String url) {
HttpGet get = new HttpGet(url);
get.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;");
get.addHeader("Accept-Language", "zh-cn");
get.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");
get.addHeader("Keep-Alive", "300");
get.addHeader("Connection", "Keep-Alive");
get.addHeader("Cache-Control", "no-cache");
return res(get);
} public String post(String url, Map<String, String> param, String cookie) {
HttpPost post = new HttpPost(url);
param.keySet().stream().forEach(key -> {
String value = param.get(key);
if(value!=null)
post.addHeader(key, value);
});
if(StringUtils.isNotBlank(cookie))
post.addHeader("cookie", cookie);
return res(post);
} public String post(String url, String data) {
HttpPost post = new HttpPost(url);
if(StringUtils.isNotBlank(data))
post.addHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(data,ContentType.APPLICATION_JSON));
return res(post);
} public String post(String url, Map<String, String> param, String cookie, Map<String, String> headers) {
HttpPost post = new HttpPost(url);
String reqEntity = "";
for(Entry<String, String> entry:param.entrySet()) {
post.addHeader(entry.getKey(), entry.getValue());
try {
reqEntity += entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "utf-8") + "&";
} catch (UnsupportedEncodingException e) {
LOG.error("请求实体转换异常,不支持的字符集,由于 " + e.getLocalizedMessage());
e.printStackTrace();
}
} try {
post.setEntity(new StringEntity(reqEntity));
} catch (UnsupportedEncodingException e) {
LOG.error("请求设置实体异常,不支持的字符集, 由于 " + e.getLocalizedMessage());
e.printStackTrace();
} if(StringUtils.isNotEmpty(cookie))
post.addHeader("cookie", cookie); return res(post);
}
}

3.参考资料:

HttpClient工具类 ——人生若只如初见

4.注意,jdk版本要求1.8以上

ok~

基于HttpClient4.5.2实现的HttpClient工具类的更多相关文章

  1. 基于HttpClient4&period;5&period;1实现Http访问工具类

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

  2. 代码片段:基于 JDK 8 time包的时间工具类 TimeUtil

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “知识的工作者必须成为自己时间的首席执行官.” 前言 这次泥瓦匠带来的是一个好玩的基于 JDK ...

  3. 封装一个基于NLog&plus;NLog&period;Mongo的日志记录工具类LogUtil

    封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,代码比较简单,主要是把MongoTarget的配置.FileTarget的配置集成到类中,同时利用缓存依赖来判断是否需要重新创 ...

  4. 封装一个基于NLog&plus;NLog&period;Mongo的日志记录工具类LogUtil,nloglogutil

    封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,代码比较简单,主要是把MongoTarget的配置.FileTarget的配置集成到类中,同时利用缓存依赖来判断是否需要重新创 ...

  5. Java开发小技巧(五):HttpClient工具类

    前言 大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具 ...

  6. Go&sol;Python&sol;Erlang编程语言对比分析及示例 基于RabbitMQ&period;Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog&plus;NLog&period;Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C&num; B&sol;S 、C&sol;S项目均可以使用!

    Go/Python/Erlang编程语言对比分析及示例   本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...

  7. 转&colon;轻松把玩HttpClient之封装HttpClient工具类&lpar;一&rpar;(现有网上分享中的最强大的工具类)

    搜了一下网络上别人封装的HttpClient,大部分特别简单,有一些看起来比较高级,但是用起来都不怎么好用.调用关系不清楚,结构有点混乱.所以也就萌生了自己封装HttpClient工具类的想法.要做就 ...

  8. 基于jdk1&period;7实现的excel导出工具类

    通用excel导出工具类,基于泛型.反射.hashmap 以及基于泛型.反射.bean两种方式 import java.io.*;import java.lang.reflect.Field;impo ...

  9. 使用单例模式实现自己的HttpClient工具类

    引子 在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient 来方便我们使用各种Http服务.你可以把HttpCli ...

随机推荐

  1. 杭电ACM2096--小明A&plus;B

    http://acm.hdu.edu.cn/showproblem.php?pid=2096 本来就是很简单.但是数据的大小有要求. (a%100+b%100)%100和(a+b)%100本来没有什么 ...

  2. 隐藏NavigationBar 带来的坑

    一.场景介绍 现在大多数APP 都有一个需求,就是隐藏某一个页面的NavigationBar.很多开发者直接   [self.navigationController setNavigationBar ...

  3. php之框架增加日志记录功能类

    <?php /* 思路:给定文件,写入读取(fopen ,fwrite……) 如果大于1M 则重写备份 传给一个内容, 判断大小,如果大于1M,备份 小于则写入 */ class Log{ // ...

  4. JQuery中回车键登陆

    //点击回车键 //王东升/2015/3/11 document.onkeydown = function (event) { var e = event ? event : (window.even ...

  5. js操作

    1.1.直接传入Javascript代码,定位元素 js可以点击页面上不显示暂时隐藏(比如下拉列表),但是html文件中存在的属性 WebDriver driver = new FirefoxDriv ...

  6. Spring Aop 应用实例与设计浅析

    0.代码概述 代码说明:第一章中的代码为了突出模块化拆分的必要性,所以db采用了真实操作.下面代码中dao层使用了打印日志模拟插入db的方法,方便所有人运行demo. 1.项目代码地址:https:/ ...

  7. ubuntu的网络配置

    1,检查网络是否通畅 ping www.baidu.com 2,检查网线是否插好 3,使用ifconfig查看当前活跃网络接口 ifconfig 4,配置IP地址.子网掩码.网关地址 sudo vi ...

  8. java第5章学习总结

    学号20145336 <Java程序设计>第5周学习总结 教材学习内容总结 try catch JVM会先尝试执行try区块中的内容,若发生错误且与catch后面的类型相符,则执行catc ...

  9. 【STM32H7教程】第13章 STM32H7启动过程详解

    完整教程下载地址:http://forum.armfly.com/forum.php?mod=viewthread&tid=86980 第13章       STM32H7启动过程详解 本章教 ...

  10. http&colon;&sol;&sol;blog&period;csdn&period;net&sol;w&lowbar;e&lowbar;i&lowbar;&sol;article&sol;details&sol;70766035

    http://blog.csdn.net/w_e_i_/article/details/70766035