HttpUtils带连接池

准备祖传了,有问题欢迎大家指正。

HttpUtil


import com.txlc.cloud.commons.exception.ServiceException;
import com.txlc.dwh.common.constants.MyErrorCode;
import org.ssssssss.script.annotation.Comment;import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;/*** @author **/
public class HttpUtil {public static final String UTF_8 = "UTF-8";private static final PooledHttpClientAdaptor adaptor = new PooledHttpClientAdaptor();@Comment("http get")public static String doGet(@Comment("url")String apiUrl, @Comment("请求头,没有请传null")Map<String, String> headers, @Comment("url参数")Map<String, Object> params) {return adaptor.doGet(apiUrl, headers, params);}public static String doFormPost(@Comment("url")String apiUrl, @Comment("请求头,没有请传null")Map<String, String> headers, @Comment("form参数")Map<String, Object> params) {return adaptor.doPost(apiUrl, headers, params);}public static String doJsonPost(@Comment("url")String apiUrl,@Comment("请求头,没有请传null") Map<String, String> headers, @Comment("json参数")String jsonParam) {try {return adaptor.doPost(apiUrl, headers, jsonParam);} catch (UnsupportedEncodingException e) {throw new ServiceException(MyErrorCode.HTTP_PARAM_JSON.getStatus(),MyErrorCode.HTTP_PARAM_JSON.getMsg());}}public static String doDelete(String url, Map<String, String> headers, HashMap<String, Object> params) {return adaptor.doDelete(url, headers, params);}public static 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 == true) {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) {}}return sb.toString();}public static Map<String, Object> convent2Map(Object b) {Map<String, Object> params = new HashMap<>();for(Field field: b.getClass().getDeclaredFields()) {field.setAccessible(true);Object val = null;try {val = field.get(b);} catch (IllegalArgumentException | IllegalAccessException e) {}if(val != null) {params.put(field.getName(), val);}}return params;}}

PooledHttpClientAdaptor


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;import javax.net.ssl.SSLContext;import cn.hutool.core.util.StrUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
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.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.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import com.alibaba.fastjson.JSON;/*** @author JGMa**/
public class PooledHttpClientAdaptor {private static final Logger logger = LoggerFactory.getLogger(PooledHttpClientAdaptor.class);private static final int DEFAULT_POOL_MAX_TOTAL = 200;private static final int DEFAULT_POOL_MAX_PER_ROUTE = 200;private static final int DEFAULT_CONNECT_TIMEOUT = 10000;private static final int DEFAULT_CONNECT_REQUEST_TIMEOUT = 10000;private static final int DEFAULT_SOCKET_TIMEOUT = 60000;private PoolingHttpClientConnectionManager gcm = null;private CloseableHttpClient httpClient = null;private IdleConnectionMonitorThread idleThread = null;// 连接池的最大连接数private final int maxTotal;// 连接池按route配置的最大连接数private final int maxPerRoute;// tcp connect的超时时间private final int connectTimeout;// 从连接池获取连接的超时时间private final int connectRequestTimeout;// tcp io的读写超时时间private final int socketTimeout;public PooledHttpClientAdaptor() {this(PooledHttpClientAdaptor.DEFAULT_POOL_MAX_TOTAL,PooledHttpClientAdaptor.DEFAULT_POOL_MAX_PER_ROUTE,PooledHttpClientAdaptor.DEFAULT_CONNECT_TIMEOUT,PooledHttpClientAdaptor.DEFAULT_CONNECT_REQUEST_TIMEOUT,PooledHttpClientAdaptor.DEFAULT_SOCKET_TIMEOUT);}public PooledHttpClientAdaptor(int maxTotal, int maxPerRoute, int connectTimeout, int connectRequestTimeout, int socketTimeout ) {this.maxTotal = maxTotal;this.maxPerRoute = maxPerRoute;this.connectTimeout = connectTimeout;this.connectRequestTimeout = connectRequestTimeout;this.socketTimeout = socketTimeout;final SSLConnectionSocketFactory sslsf;try {sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(),NoopHostnameVerifier.INSTANCE);} catch (NoSuchAlgorithmException e) {throw new RuntimeException(e);}Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();this.gcm = new PoolingHttpClientConnectionManager(registry);this.gcm.setMaxTotal(this.maxTotal);this.gcm.setDefaultMaxPerRoute(this.maxPerRoute);RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(this.connectTimeout)                     // 设置连接超时.setSocketTimeout(this.socketTimeout)                       // 设置读取超时.setConnectionRequestTimeout(this.connectRequestTimeout)    // 设置从连接池获取连接实例的超时.build();HttpClientBuilder httpClientBuilder = HttpClients.custom();httpClient = httpClientBuilder.setConnectionManager(this.gcm).setDefaultRequestConfig(requestConfig).build();idleThread = new IdleConnectionMonitorThread(this.gcm);idleThread.start();}public String doGet(String url) {return this.doGet(url, Collections.emptyMap(), Collections.emptyMap());}public String doGet(String url, Map<String, Object> params) {return this.doGet(url, Collections.emptyMap(), params);}public String doGet(String url, Map<String, String> headers,Map<String, Object> params) {logger.debug("doGet url:" + url + ". headers :" + JSON.toJSONString(headers) + ". params :" + JSON.toJSONString(params));// *) 构建GET请求头String apiUrl = HttpUtil.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());}}CloseableHttpResponse response = null;try {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, HttpUtil.UTF_8);}}return null;} catch (IOException e) {logger.error(e.getMessage(), e);} finally {if ( response != null ) {try {response.close();} catch (IOException e) {}}}return null;}public String doPost(String apiUrl, Map<String, Object> params) {return this.doPost(apiUrl, Collections.emptyMap(), params);}public String doPost(String apiUrl,Map<String, String> headers,String jsonParam) throws UnsupportedEncodingException {logger.debug("doPost url:" + apiUrl + ". headers :" + JSON.toJSONString(headers) + ". jsonParam :" + jsonParam);HttpPost httpPost = new HttpPost(apiUrl);// 配置请求headersif ( headers != null && headers.size() > 0 ) {for (Map.Entry<String, String> entry : headers.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());}}// 配置请求参数if ( StrUtil.isNotBlank(jsonParam)) {StringEntity jsonEntity = new StringEntity(jsonParam);httpPost.setEntity(jsonEntity);httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");}CloseableHttpResponse response = null;try {response = httpClient.execute(httpPost);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, HttpUtil.UTF_8);}}return null;} catch (IOException e) {logger.error(e.getMessage(), e);} finally {if (response != null) {try {response.close();} catch (IOException e) {}}}return null;}public String doPost(String apiUrl,  Map<String, String> headers, Map<String, Object> params) {logger.debug("doPost url:" + apiUrl + ". headers :" + JSON.toJSONString(headers) + ". params :" + JSON.toJSONString(params));HttpPost httpPost = new HttpPost(apiUrl);// 配置请求headersif ( headers != null && headers.size() > 0 ) {for (Map.Entry<String, String> entry : headers.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());}}// 配置请求参数if ( params != null && params.size() > 0 ) {HttpEntity entityReq = getUrlEncodedFormEntity(params);httpPost.setEntity(entityReq);}CloseableHttpResponse response = null;try {response = httpClient.execute(httpPost);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, HttpUtil.UTF_8);}}return null;} catch (IOException e) {logger.error(e.getMessage(), e);} finally {if (response != null) {try {response.close();} catch (IOException e) {}}}return null;}public String doDelete(String url,  Map<String, String> headers, Map<String, Object> params) {logger.info("doDelete url:" + url + ". headers :" + JSON.toJSONString(headers) + ". params :" + JSON.toJSONString(params));HttpDelete httpDelete = new HttpDelete(url);// *) 设置header信息if ( headers != null && headers.size() > 0 ) {for (Map.Entry<String, String> entry : headers.entrySet()) {httpDelete.addHeader(entry.getKey(), entry.getValue());}}CloseableHttpResponse response = null;try {response = httpClient.execute(httpDelete);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, HttpUtil.UTF_8);}}return null;} catch (IOException e) {logger.error(e.getMessage(), e);} finally {if ( response != null ) {try {response.close();} catch (IOException e) {}}}return null;}private HttpEntity getUrlEncodedFormEntity(Map<String, Object> params) {List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());for (Map.Entry<String, Object> entry : params.entrySet()) {NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());pairList.add(pair);}return new UrlEncodedFormEntity(pairList, Charset.forName(HttpUtil.UTF_8));}public void shutdown() {idleThread.shutdown();}// 监控有异常的链接private class IdleConnectionMonitorThread extends Thread {private final HttpClientConnectionManager connMgr;private volatile boolean exitFlag = false;public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {this.connMgr = connMgr;setDaemon(true);}@Overridepublic void run() {while (!this.exitFlag) {synchronized (this) {try {this.wait(2000);} catch (InterruptedException e) {e.printStackTrace();}}// 关闭失效的连接connMgr.closeExpiredConnections();// 可选的, 关闭30秒内不活动的连接connMgr.closeIdleConnections(30, TimeUnit.SECONDS);}}public void shutdown() {this.exitFlag = true;synchronized (this) {notify();}}}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/81346.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JAVA入坑之嵌套类

一、嵌套类入门 1.1概述 Java嵌套类是指在一个类中定义另一个类的一种方式&#xff0c;它可以提高代码的可读性、可维护性和封装性。Java嵌套类分为两种类型&#xff1a;静态嵌套类和非静态嵌套类。 静态嵌套类&#xff1a;Static nested classes,即类前面有static修饰符 非静…

【论文解读】Faster sorting algorithm

一、简要介绍 基本的算法&#xff0c;如排序或哈希&#xff0c;在任何一天都被使用数万亿次。随着对计算需求的增长&#xff0c;这些算法的性能变得至关重要。尽管在过去的2年中已经取得了显著的进展&#xff0c;但进一步改进这些现有的算法路线的有效性对人类科学家和计算方法…

Prometheus PromQL数据查询语言

PromQL 简介 PromQL&#xff08;Prometheus Query Language&#xff09;是 Prometheus 内置的数据查询语言。支持用户进行实时的数据查询及聚合操作。 Prometheus 基于指标名称&#xff08;metrics name&#xff09;以及附属的标签集&#xff08;labelset&#xff09;唯一定义一…

2023-09-17 LeetCode每日一题(打家劫舍 II)

2023-09-17每日一题 一、题目编号 213. 打家劫舍 II二、题目链接 点击跳转到题目位置 三、题目描述 你是一个专业的小偷&#xff0c;计划偷窃沿街的房屋&#xff0c;每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 &#xff0c;这意味着第一个房屋和最后一个房…

《golang设计模式》第二部分·结构型模式-05-门面模式Facade)

文章目录 1. 概述1.1 角色1.2 类图 2. 代码示例2.1 设计2.2 代码2.2 类图 1. 概述 门面&#xff08;Facade&#xff09;向客户端提供使用子系统的统一接口&#xff0c;用于简化客户端使用子系统的操作。 1.1 角色 门面角色&#xff08;Facade&#xff09; 客户端可以调用的接…

svg图片代码data:image/svg+xml转png图片方法

把代码保存为html格式的文件中,用浏览器访问,即可右键保存 从AI软件或其它网站得到svg图片代码后,把他复制到下面源码上 注意:src""图片地址中,一些参数的含义 d‘这里是图片代码数据’ viewBox是图片显示区域,宽,高等 fill%23000000’这里表示颜色 ,后面6位0表示黑色…

Vercel.json配置路由重定向(重写)【vue项目】

在项目根目录创建vercel.json {"rewrites": [{"source": "/(.*)","destination": "/"}] } vue-router 路由模式改为 history&#xff08;vue2版本&#xff09; createWebHistory&#xff08;vue3版本&#xff09;

7、DVWA——SQL盲注

文章目录 一、概述二、low2.1 通关思路&#xff08;布尔盲注&#xff09;&#xff08;1&#xff09;判断是否存在SQL注入漏洞&#xff08;2&#xff09;判断属于数字型注入还是字符型注入&#xff08;3&#xff09;判断结果集中的字段数&#xff08;4&#xff09;猜数据库名长度…

ArcGIS Pro将SHP文件转CAD并保留图层名称

相信大家应该都使用过ArcGIS将SHP文件转CAD格式&#xff0c;转换过后所有的要素都在一个图层内&#xff0c;那么有没有办法将SHP文件某个字段的值作为CAD的图层名字呢&#xff0c;答案是肯定的&#xff0c;这里就为大家介绍一下ArcGIS Pro转CAD文件并且保留图层名称的方法&…

Windows编程dll基本知识点

前言 本篇博客主要是记录windows系统下dll开发的相关基本知识点&#xff0c;并使用相关分析工具分析&#xff0c;有利于初学者学习&#xff0c;更是为开发者查缺补漏&#xff1b; 使用dumpbin查看dll,lib,exe相关信息 VS编译器提供了查看链接库相关的工具&#xff0c;安装后…

【c++GDAL】IHS融合

【c&GDAL】IHS融合 基于IHS变换融合&#xff0c;实现多光谱和全色影像之间的融合。IHS分别指亮度(I)、色度(H)、饱和度(S)。IHS变换融合基于亮度I进行变换&#xff0c;色度和饱和度空间保持不变。 IHS融合步骤&#xff1a; &#xff08;1&#xff09;将多光谱RGB影像变换到…

网络安全:保护你的系统

&#x1f337;&#x1f341; 博主猫头虎&#xff08;&#x1f405;&#x1f43e;&#xff09;带您 Go to New World✨&#x1f341; &#x1f984; 博客首页——&#x1f405;&#x1f43e;猫头虎的博客&#x1f390; &#x1f433; 《面试题大全专栏》 &#x1f995; 文章图文…

FLASK中的鉴权的插件Flask-HTTPAuth

在 Web 应用中&#xff0c;我们经常需要保护我们的 api&#xff0c;以避免非法访问。比如&#xff0c;只允许登录成功的用户发表评论等。Flask-HTTPAuth 扩展可以很好地对 HTTP 的请求进行认证&#xff0c;不依赖于 Cookie 和 Session。本文主要介绍两种认证的方式&#xff1a;…

地牢大师问题(bfs提高训练 + 免去边界处理的特殊方法)

地牢大师问题 文章目录 地牢大师问题前言题目描述题目分析输入处理移动方式【和二维的对比】边界判断问题的解决 代码总结 前言 在之前的博客里面&#xff0c;我们介绍了bfs 基础算法的模版和应用,这里我们再挑战一下自己&#xff0c;尝试一个更高水平的题目&#xff0c;加深一…

点云从入门到精通技术详解100篇-基于点云语义分割的电力线提取及聚类研究(下)

目录 3.4.3 MSIDA-Net 与主成分分析法对比 基于簇最低点聚类算法的电力线聚类及重建

Docker部署单点Elasticsearch与Kibana

一 、 创建网络 因为需要部署kibana容器&#xff0c;因此需要让es和kibana容器互联。这里创建一个网络&#xff1a; docker network create es-net # 创建一个网络名称为:es-net 二 、拉取并加载镜像 方式一 docker pull elasticsearch:7.12.1 版本为elasticsearch的7…

列属性与数据完整性

1.2 数据类型——值类型 1.2.1 整型 类型字节范围tinyint1-128~127smallint2-32768~32767mediumint3-8388608~8388607int4-231~231-1bigint8-263~263-1 1、无符号整数&#xff08;unsigned&#xff09;&#xff1a;无符号数没有负数&#xff0c;正数部分是有符号的两倍。 例…

Linux驱动之INPUT子系统框架

目录 一、input 子系统简介 二、input 驱动编写流程 1、注册 input_dev 2、上报输入事件 三、input_event 结构体 按键、鼠标、键盘、触摸屏等都属于输入(input)设备&#xff0c; Linux 内核为此专门做了一个叫做 input子系统的框架来处理输入事件。输入设备本质上还是字符设…

Go语言开发环境搭建指南:快速上手构建高效的Go开发环境

Go 官网&#xff1a;https://go.dev/dl/ Go 语言中文网&#xff1a;https://studygolang.com/dl 下载 Go 的语言包 进入官方网站 Go 官网 或 Go 语言中文网&#xff1a; 选择下载对应操作系统的安装包&#xff1a; 等待下载完成&#xff1a; 安装 Go 的语言包 双击运行上…

udp的简单整理

最近思考udp处理的一些细节&#xff0c;根据公开课&#xff0c;反复思考&#xff0c;终于有所理解&#xff0c;做整理备用。 0&#xff1a;简单汇总 1&#xff1a;udp是基于报文传输的&#xff0c;接收方收取数据时要一次性读完。 2&#xff1a;借助udp进行发包&#xff0c;…