Apache HttpClient 4.5 在Springboot中使用
ConnectionRequestTimeout
httpclient使用连接池来管理连接,这个时间就是从连接池获取连接的超时时间,可以想象下数据库连接池
ConnectTimeout
连接建立时间,三次握手完成时间
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.13</version>
</dependency>
然后新建httpclient类:
在dopost中可以根据业务自定义逻辑
@Slf4j
@Service
public class HttpClientFactory {
@Autowired
HttpClientConfig httpClientConfig;
private PoolingHttpClientConnectionManager poolConnManager;
// 线程安全,所有的线程都可以使用它一起发送http请求
private CloseableHttpClient httpClient;
@PostConstruct
public void init() {
try {
log.info("init http client start, default config is {}", httpClientConfig);
SSLConnectionSocketFactory trustAll = buildSSLContext();
// 配置同时支持 HTTP 和 HTTPS
// 一个httpClient对象对于https仅会选用一个SSLConnectionSocketFactory
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().
register("http", PlainConnectionSocketFactory.getSocketFactory()).
register("https", trustAll).build();
// 初始化连接管理器
poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
poolConnManager.setMaxTotal(httpClientConfig.getPollMaxTotal());// 同时最多连接数
// 设置最大路由
poolConnManager.setDefaultMaxPerRoute(httpClientConfig.getPollMaxPeerRouter());
httpClient = getConnection();
log.info("init http client finish");
} catch (Exception e) {
log.error("", e);
}
}
public CloseableHttpClient getConnection() {
RequestConfig config = RequestConfig.custom().setConnectTimeout(httpClientConfig.getConnectTimeout())
.setConnectionRequestTimeout(httpClientConfig.getConnectionRequestTimeout())
.setSocketTimeout(httpClientConfig.getResponseTimeout())
.build();
return HttpClients.custom()
// 设置连接池管理
.setConnectionManager(poolConnManager)
.setDefaultRequestConfig(config).build();
}
public String doGet(String url) {
return this.doGet(url, Collections.EMPTY_MAP, Collections.EMPTY_MAP);
}
public String doGet(String url, Map<String, Object> params) {
return this.doGet(url, Collections.EMPTY_MAP, params);
}
public String doGet(String url, Map<String, String> headers, Map<String, Object> params) {
// *) 构建GET请求头
String apiUrl = getUrlWithParams(url, params);
HttpGet httpGet = new HttpGet(apiUrl);
// *) 设置header信息
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
if (response == null || response.getStatusLine() == null) {
return null;
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entityRes = response.getEntity();
if (entityRes != null) {
return EntityUtils.toString(entityRes, "UTF-8");
}
}
return null;
} catch (IOException e) {
log.error("", e);
}
return null;
}
public HttpServerResponseDTO doPost(String apiUrl, String body, int connectionTimeOut, Integer contentTypeEnum, String pemBody) {
return doPost(apiUrl, Collections.EMPTY_MAP, body, connectionTimeOut, contentTypeEnum);
}
public HttpServerResponseDTO doPost(String apiUrl, Map<String, String> headers, String body,Integer contentTypeEnum) {
CloseableHttpClient currentHttpClient = httpClient;
HttpPost httpPost = new HttpPost(apiUrl);
// *) 配置请求headers
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
ContentTypeEnum contentType = ContentTypeEnum.getDataSourceEnum(contentTypeEnum);
// *) 配置请求参数
httpPost.setEntity(new StringEntity(body, ContentType.create(contentType.getDesc(), Consts.UTF_8)));
httpPost.setConfig(buildRequestConfig());
try (CloseableHttpResponse response = currentHttpClient.execute(httpPost)) {
if (response == null || response.getStatusLine() == null) {
return HttpServerResponseDTO.builder()
.statusCode(Constants.HTTP_CLIENT_ERROR)
.build();
}
HttpEntity httpEntity = response.getEntity();
String contentTypeString = httpEntity.getContentType() == null ? null : httpEntity.getContentType().getValue();
String connection = getHeaderValue(response, "Connection");
String server = getHeaderValue(response, "Server");
String date = getHeaderValue(response, "Date");
String pragma = getHeaderValue(response, "pragma");
return HttpServerResponseDTO.builder()
.statusCode(response.getStatusLine().getStatusCode())
.body(EntityUtils.toString(response.getEntity(), UTF_8))
.contentType(contentTypeString)
.connection(connection)
.server(server)
.date(date)
.pragma(pragma)
.build();
} catch (IOException e) {
log.error("", e);
return HttpServerResponseDTO.builder().statusCode(Constants.HTTP_CLIENT_ERROR).statusMessage(e.getMessage()).build();
}
}
private String getUrlWithParams(String url, Map<String, Object> params) {
boolean first = true;
StringBuilder sb = new StringBuilder(url);
for (String key : params.keySet()) {
char ch = '&';
if (first) {
ch = '?';
first = false;
}
String value = params.get(key).toString();
try {
String sval = URLEncoder.encode(value, "UTF-8");
sb.append(ch).append(key).append("=").append(sval);
} catch (UnsupportedEncodingException e) {
log.error("", e);
}
}
return sb.toString();
}
public SSLConnectionSocketFactory buildSSLContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException {
SSLContext sslcontext = SSLContexts.custom()
//忽略掉对服务器端证书的校验
.loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
.build();
return new SSLConnectionSocketFactory(
sslcontext,
new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"},
null,
NoopHostnameVerifier.INSTANCE);
}
private RequestConfig buildRequestConfig() {
int connectionOut = httpClientConfig.getConnectTimeout();
return RequestConfig.custom().setConnectTimeout(connectionOut)
.setConnectionRequestTimeout(httpClientConfig.getConnectionRequestTimeout())
.setSocketTimeout(connectionOut)
.build();
}
private String getHeaderValue(CloseableHttpResponse response, String key) {
return response.getFirstHeader(key) == null ?
null : response.getFirstHeader(key).getValue();
}
}
调用方式:
@Autowired
HttpClientFactory httpClientFactory;
HttpServerResponseDTO httpServerResponseDTO = httpClientFactory.doPost(url, headersMap, body, httpConfigEntity.getContentType(), httpConfigEntity.getTls());
Apache HttpClient 4.5 在Springboot中使用的更多相关文章
- 在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类
推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,androi ...
- android 中对apache httpclient及httpurlconnection的选择
在官方blog中,android工程师谈到了如何去选择apache client和httpurlconnection的问题: 原文见http://android-developers.blogspot ...
- 如何在Apache HttpClient中设置TLS版本
1.简介 Apache HttpClient是一个底层.轻量级的客户端HTTP库,用于与HTTP服务器进行通信. 在本教程中,我们将学习如何在使用HttpClient时配置支持的传输层安全(TLS)版 ...
- springboot 中使用Druid 数据源提供数据库监控
一.springboot 中注册 Servlet/Filter/Listener 的方式有两种,1 通过代码注册 ServletRegistrationBean. FilterRegistration ...
- 如何在SpringBoot中使用JSP ?但强烈不推荐,果断改Themeleaf吧
做WEB项目,一定都用过JSP这个大牌.Spring MVC里面也可以很方便的将JSP与一个View关联起来,使用还是非常方便的.当你从一个传统的Spring MVC项目转入一个Spring Boot ...
- Apache HttpClient使用之阻塞陷阱
前言: 之前做个一个数据同步的定时程序. 其内部集成了某电商的SDK(简单的Apache Httpclient4.x封装)+Spring Quartz来实现. 原本以为简单轻松, 喝杯咖啡就高枕无忧的 ...
- Android 6.0删除Apache HttpClient相关类的解决方法
相应的官方文档如下: 上面文档的大致意思是,在Android 6.0(API 23)中,Google已经移除了Apache HttpClient相关的类,推荐使用HttpUrlConnection. ...
- spring-boot+mybatis开发实战:如何在spring-boot中使用myabtis持久层框架
前言: 本项目基于maven构建,使用mybatis-spring-boot作为spring-boot项目的持久层框架 spring-boot中使用mybatis持久层框架与原spring项目使用方式 ...
- 新旧apache HttpClient 获取httpClient方法
在apache httpclient 4.3版本中对很多旧的类进行了deprecated标注,通常比较常用的就是下面两个类了. DefaultHttpClient -> CloseableHtt ...
随机推荐
- JavaScript 究竟是怎样去执行的?
摘要: 理解 JS 引擎运行原理. 作者:前端小智 原文:搞懂 JavaScript 引擎运行原理 Fundebug经授权转载,版权归原作者所有. 一些名词 JS 引擎 — 一个读取代码并运行的引擎, ...
- webpack做项目优化
webpack优化 -- compression-webpack-plugin 开启gzip 打包的时候开启gzip可以大大减少体积,非常适合于上线部署.下面以vue-cli2.x项目为例,介绍如何在 ...
- 2020重新出发,NOSQL,redis高并发系统的分析和设计
高并发系统的分析和设计 任何系统都不是独立于业务进行开发的,真正的系统是为了实现业务而开发的,所以开发高并发网站抢购时,都应该先分析业务需求和实际的场景,在完善这些需求之后才能进入系统开发阶段. 没有 ...
- Zabbix value cache working in low memory mode
Zabbix监控自身时告警"Zabbix value cache working in low memory mode",出现这个问题是因为Zabbix Server的参数Valu ...
- Html中让输入框input和紧接在后的按钮button在垂直方向上对齐
<table border="0px" width="360px"> <tr><td colspan="10" ...
- Tomcat7.0.99集群使用Redis共享session方案
以前配置过给予多播的session共享方案,这回再配置一个redis共享session的. 先小小的炫耀一下: 相信大家要做Tomcat+Redis+session配置,遇到的头号麻烦就是编译的tom ...
- i春秋公益赛之signin
题目链接:https://buuoj.cn/challenges#gyctf_2020_signin 查看程序保护 只开了canary和NX保护,在IDA查看反编译出来的为代码时发现程序给了一个后门 ...
- hacker101 CTF 学习记录(二)
前言 无 Easy-Postbook 拿到功能有点多,先扫一遍目录 .Ds_Store没有啥东西,page是个静态页面 随便注册个账号,登录后已经有2篇文章,第一篇文章的id是1 自己创建文章,将ur ...
- JavaScript 伪Ajax请求
伪Ajax 通过iframe以及form表单,可以实现伪Ajax的方式. 并且它的兼容性是最好的. iframe iframe标签能够获取一个其他页面的文档内容,这说明它内部肯定是发送了一个请求,并且 ...
- [LeetCode] 279. 完全平方数(DP)
###题目 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n.你需要让组成和的完全平方数的个数最少. 示例 1: 输入: n = 12 输出: 3 解 ...