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();}}}}
相关文章:
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; impo…...
智慧养殖:浅谈视频监控与AI智能识别技术助力奶牛高效、智慧养殖
一、方案背景 随着科技的飞速发展,智能化养殖逐渐成为现代畜牧业的发展趋势。人工智能技术、物联网、视频技术、云计算、大数据等新兴技术,正在为奶牛养殖业带来全新的变革。越来越多的牧场、养殖场开始运用新技术来进行智能监管、提高生产效率、降低生…...
一文总结提示工程框架,除了CoT还有ToT、GoT、AoT、SoT、PoT
夕小瑶科技说 原创 编译 | 谢年年 大语言模型LLM被视为一个巨大的知识库,它可以根据你提出问题或陈述的方式来提供答案。就像人类可能会根据问题的不同提供不同的答案一样,LLM也可以根据输入的不同给出不同的答案。因此,你的问题或陈述方式就…...
Java面试笔试acm版输入
首先区分scanner.nextInt()//输入一个整数,只能读取一个数,空格就停止。 scanner.next()//输入字符串,只能读取一个字符串,空格就停止,但是逗号不停止。 scanner.nextLine() 读取一行,换行停止,…...
新手怎样快速上手接口测试?掌握这几个知识点直接起飞!
接口测试是测试系统组件间接口的一种方式,接口测试主要用于检测外部系统与系统之间以及内部各个子系统之间的交互点。测试的重点是检查数据的增删改查操作,以及系统之间的逻辑关系等。 接口的几种类型 接口的类型包括:post ,get&…...
IDEA 启动 java web 老项目
背景:一套 java web 老代码,使用 eclipse 工具开发。内网,无 eclipse 开发工具,只有 IDEA。 代码目录结构如下: demo/.settings/* demo/src/com/demo/controller/* demo/webapp/js/* demo/webapp/jsp/* demo/webapp/M…...
软路由和硬路由的区别是什么,性价比与可玩性分析
软路由和硬路由是两种不同类型的路由器设备,它们在基本原理、功能、性能和灵活性等方面存在一些区别: 硬件:软路由是基于一台普通的计算机或服务器,通过软件来实现路由器的功能;而硬路由是专门设计的硬件设备ÿ…...
《TCP/IP网络编程》阅读笔记--多线程服务器端的实现
目录 1--多线程的优点 2--进程和线程的差异 3--线程创建 4--线程使用 5--线程安全问题 6--互斥量 7--信号量 8--线程销毁 9--多线程并发聊天程序 9-1--服务器端 9-2--客户端 9-3--测试结果 1--多线程的优点 多进程服务器的缺点: ① 创建进程的过程会带来…...
修改el-card的header的背景颜色
修改el-card的header的背景颜色 1.修改默认样式 好处是当前页面的所有的el-card都会变化 页面卡片: <el-card class"box-card" ><div slot"header" class"clearfix"><span>卡片名称</span><el-button s…...
ubuntu系统中查看打开的端口
要查看Ubuntu系统中已打开的端口及其相关信息,可以使用以下方法: 打开终端(Terminal)。 运行以下命令以查看当前系统中的端口使用情况: sudo netstat -tuln这将显示所有已打开的端口及其相关信息,包括监听…...
Datax从mysql同步数据到HDFS
在实际使用Datax的时候,比较常用的是同步业务数据(mysql中的数据)到HDFS来实现数仓的创建,那么怎么实现呢?我们一步步来实现(基于Datax 3.0.0) 1、检查环境,需要安装完一个Datax&am…...
使用 Selenium 或其他工具模拟浏览器使用及语法代码
使用Selenium模拟浏览器使用的代码示例如下: from selenium import webdriverfrom selenium.webdriver.common.keys import Keys# 创建浏览器驱动实例driver webdriver.Chrome()# 打开网页driver.get("https://www.example.com")# 查找并填写表单search_…...
华为手机如何开启设置健康使用手机模式限制孩子玩手机时间?
华为手机如何开启设置健康使用手机模式限制孩子玩手机时间? 1、在手机上找到「设置」并点击打开; 2、在设置内找到「健康使用手机」并点击进入; 3、开启健康使用手机后,选择孩子使用; 4、在健康使用手机内,…...
【Linux】线程池 | 自旋锁 | 读写锁
文章目录 一、线程池1. 线程池模型和应用场景2. 单例模式实现线程池(懒汉模式) 二、其他常见的锁1. STL、智能指针和线程安全2. 其他常见的锁 三、读者写者问题1. 读者写者模型2. 读写锁 一、线程池 1. 线程池模型和应用场景 线程池是一种线程使用模式。线程过多会带来调度开…...
[网鼎杯 2020 青龙组]bang 题解
写一道安卓题的WP 首先你需要一个root机,使用真机或者虚拟机,根据网上的教程刷机并获取root 我使用真机调试,pixel2 讲安卓包下载到真机 在PC端配置frida 对应版本的server传送到/data/local/tmp 然后进行以上操作,启动server …...
创建环境时提示:ERROR conda.core.link:_execute(502)
创建环境时提示:ERROR conda.core.link:_execute(502) 创建环境最后Executing transaction,失败,提示如下: Preparing transaction: done Verifying transaction: done Executing transaction: failed ERROR conda.core.link:_e…...
Python150题day07
1.5集合练习题 集合间的运算 lst1 [1, 2, 3, 5, 6, 3, 2] lst2 [2, 5, 7, 9] 哪些整数既在Ist1中,也在Ist2中哪些整数在Ist1中,不在Ist2中两个列表一共有哪些整数 虽然题目问的是两个列表之间的问题,但是用列表解答的效率很低,…...
LeetCode 2596. 检查骑士巡视方案
【LetMeFly】2596.检查骑士巡视方案 力扣题目链接:https://leetcode.cn/problems/check-knight-tour-configuration/ 骑士在一张 n x n 的棋盘上巡视。在有效的巡视方案中,骑士会从棋盘的 左上角 出发,并且访问棋盘上的每个格子 恰好一次 。…...
大数据学习1.0-目录
学习内容持续更新ing 1.大数据学习1.1-Centos8虚拟机安装 大数据学习1.0-Centos8虚拟机安装_汉卿HanQ的博客-CSDN博客 2.大数据学习1.2-yum配置 大数据学习1.2-yum配置_汉卿HanQ的博客-CSDN博客 3.大数据学习1.3-xShell配置jdk 大数据学习1.3-xShell配置jdk_汉卿HanQ的博客…...
无涯教程-JavaScript - POWER函数
描述 POWER函数返回加到幂的数字的输出。 语法 POWER (number, power)争论 Argument描述Required/OptionalNumber 基数。 它可以是任何实数。 RequiredPowerThe exponent to which the base number is raised.Required Notes 可以使用" ^"运算符代替POWER来指示…...
告别Widgets?用QtQuick和QML为你的桌面应用注入现代感(附完整Demo)
从Qt Widgets到QtQuick:打造现代桌面应用的实战指南 在桌面应用开发领域,Qt框架一直以其跨平台能力和稳定性著称。然而,随着用户对界面体验要求的提升,传统的Widgets方式逐渐显露出局限性——动画生硬、响应迟钝、与现代操作系统风…...
如何让实验室管理“更简单”?——King’s LIMS以灵活与智能,重构高效运营新范式
在日常实验室管理中,流程繁琐、数据难溯源、报告生成低效、多场景管控混乱等问题,常成为拖慢运营节奏、抬升运维成本的“隐形阻力”。要打破管理困局、实现轻量化高效运维,选对数字化工具是关键。然而,在选择LIMS的过程中…...
零代码玩转OpenClaw:ollama-QwQ-32B自动化脚本生成教程
零代码玩转OpenClaw:ollama-QwQ-32B自动化脚本生成教程 1. 为什么选择OpenClawollama-QwQ-32B组合? 上周我在整理旅行照片时,面对上千张命名混乱的图片文件,突然意识到:这不正是测试OpenClaw自动化能力的绝佳场景吗&…...
利用快马平台快速构建免费节点测试工具原型,十分钟完成开发
今天想和大家分享一个快速验证免费节点可用性的小工具开发过程。作为一个经常需要测试代理节点的开发者,手动一个个验证实在太费时间,于是我用InsCode(快马)平台快速搭建了一个原型工具,整个过程比想象中简单很多。 需求分析 免费节点测试工具…...
这份榜单够用!盘点2026年用户挚爱的一键生成论文工具
一天写完毕业论文在2026年已不再是天方夜谭。以下是2026年最炸裂、实测能大幅提速的一键生成论文工具,覆盖选题构思、文献综述、数据整理、格式排版等核心场景,高效搞定论文不再只是梦想。 一、全流程王者:一站式搞定论文全链路(一…...
AutoSar标准文档下载全攻略:从官网入口到模块选择(附命名规则解析)
AutoSar标准文档高效获取与深度解析指南 引言 在汽车电子系统开发领域,AutoSar标准已经成为行业公认的架构规范。无论是ECU开发工程师、系统架构师还是测试验证人员,都需要频繁查阅AutoSar官方文档。然而,面对庞大的文档体系和复杂的命名规则…...
英雄联盟智能助手:5个核心功能彻底改变你的游戏体验
英雄联盟智能助手:5个核心功能彻底改变你的游戏体验 【免费下载链接】League-Toolkit 兴趣使然的、简单易用的英雄联盟工具集。支持战绩查询、自动秒选等功能。基于 LCU API。 项目地址: https://gitcode.com/gh_mirrors/le/League-Toolkit 还在为繁琐的游戏…...
CentOS7-IP配置记录
简要说明 本文章主要记录CentOS7系统在桥接网络类型下的IP配置测试,主要分为静态和动态配置,以下部署配置仅作参考,可根据实际情况调整。 相关文章 CentOS7部署参考文章:VMware-CentOS7最小化安装记录 CentOS7指令参考文章&am…...
OpenClaw多场景实战:Qwen3-VL:30B在飞书中的5个应用案例
OpenClaw多场景实战:Qwen3-VL:30B在飞书中的5个应用案例 1. 为什么选择OpenClawQwen3-VL:30B组合 去年我在团队内部尝试搭建智能助手时,发现市面上大多数方案要么需要将敏感数据上传到第三方平台,要么功能过于单一。直到遇到OpenClaw这个开…...
Cesium1.95内存优化实战:从3D Tiles到GPU Instancing的完整避坑指南
Cesium1.95内存优化实战:从3D Tiles到GPU Instancing的完整避坑指南 在三维地理信息系统和智慧城市项目中,Cesium作为领先的WebGL框架,其性能表现直接决定了复杂场景的流畅度。当遇到大规模模型加载时,内存溢出成为开发者最头疼的…...
