最新要闻
- 世界新动态:开展12600余项减排项目 广东持续打好臭氧污染防治攻坚战
- 惠誉下调美国不动产相关产业评级展望至恶化 滚动
- 当前速讯:2023西安钟南山南五台景区高考免费活动
- 广东一考生着急进考场跑掉洞洞鞋:焦急光脚跑向考场_天天视点
- 高考时间为何定在6月?少数人能猜到 天天新消息
- 国产替代重大进步!华为100%自研数据库亮相 中国金融云第一
- 【天天快播报】AirPower“精神续作”?苹果新iPad专利塞满磁性线圈
- 上市不到1个月 要打比亚迪宋的哈弗枭龙系列有优惠了:立省6000块!
- 警用无人机空中巡飞护航高考
- 凌玮科技:6月6日融资买入132.66万元,融资融券余额4331.19万元
- 环球最新:我国部署实施2023年公海自主休渔措施
- 【全球快播报】香港警方国安处拘捕6人 其中2人涉嫌危害国家安全
- 北京城区供水已超去年最高日供水量 夏季高峰供水保障开启
- 漳州市应急管理综合执法支队准执法保安全 护航企业促发展_每日动态
- 世界快资讯丨国内首个全栈自主数据库!华为云GaussDB迈出关键一步
- 今日快看!《敢死队4》新海报公布:杰森·斯坦森变男主!
广告
手机
iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?
警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案
- iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?
- 警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案
- 男子被关545天申国赔:获赔18万多 驳回精神抚慰金
- 3天内26名本土感染者,辽宁确诊人数已超安徽
- 广西柳州一男子因纠纷杀害三人后自首
- 洱海坠机4名机组人员被批准为烈士 数千干部群众悼念
家电
全球热讯:java HttpClient工具类
(资料图片仅供参考)
package com.hl.dziot.util;import com.alibaba.fastjson.JSONObject;import com.hl.dziot.entity.PageResult;import lombok.SneakyThrows;import org.apache.http.Consts;import org.apache.http.HttpEntity;import org.apache.http.HttpStatus;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.*;import org.apache.http.client.protocol.HttpClientContext;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.entity.mime.content.StringBody;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.apache.logging.log4j.util.Strings;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.File;import java.io.FileInputStream;import java.util.Iterator;import java.util.Map;/** * HttpClient工具类 **/public class HttpClientUtil { private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); /** * 设备地址 */ public static CloseableHttpClient httpClient; private final static String USER_NAME = "admin"; private final static String PASS_WORD = "hik12345"; private final static String PREFIX = "http"; public static void httpClient() { // 摘要认证 CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASS_WORD)); RequestConfig requestConfig = RequestConfig .custom() // (ms) .setConnectTimeout(50000) .setSocketTimeout(50000) .setConnectionRequestTimeout(10) .build(); httpClient = HttpClients .custom() .setDefaultRequestConfig(requestConfig) .setDefaultCredentialsProvider(credentialsProvider) .build(); } @SneakyThrows public static PageResult> doPostFormDataForAddFace(String url, String params, File file, String employeeNo) { logger.info("参数信息 = {}", params); logger.info("请求地址 = {}", url); httpClient(); CloseableHttpResponse response; try { HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("json", new StringBody(params, ContentType.create("application/json", Consts.UTF_8))); builder.addBinaryBody("image", file, ContentType.create("image/jpeg"), employeeNo + ".jpg"); HttpEntity reqEntity = builder.build(); httpPost.setEntity(reqEntity); // 发起请求 并返回请求的响应 response = httpClient.execute(httpPost, HttpClientContext.create()); String resResult = EntityUtils.toString(response.getEntity(), "utf-8"); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return ResultUtil.success(JSONObject.parseObject(resResult)); } else { return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult)); } } catch (Exception e) { e.printStackTrace(); return ResultUtil.error(); } finally { httpClient.close(); } } @SneakyThrows public static PageResult> doPutFormDataForUpdateFace(String url, String params, File file, String employeeNo) { logger.info("参数信息 = {}", params); logger.info("请求地址 = {}", url); httpClient(); CloseableHttpResponse response = null; try { HttpPut put = new HttpPut(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 人脸信息 builder.addPart("json", new StringBody(params, ContentType.create("application/json", Consts.UTF_8))); // 图片信息 builder.addBinaryBody("image", file, ContentType.create("image/jpeg"), employeeNo + ".jpg"); HttpEntity reqEntity = builder.build(); put.setEntity(reqEntity); // 发起请求 并返回请求的响应 response = httpClient.execute(put, HttpClientContext.create()); String resResult = EntityUtils.toString(response.getEntity(), "utf-8"); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return ResultUtil.success(JSONObject.parseObject(resResult)); } else { return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult)); } } catch (Exception e) { e.printStackTrace(); return ResultUtil.error(); } finally { httpClient.close(); } } @SneakyThrows public static PageResult> doPostJson(String url, String params) { logger.info("参数信息 = {}", params); logger.info("请求地址 = {}", url); httpClient(); CloseableHttpResponse response = null; String resResult = ""; try { HttpPost post = new HttpPost(url); post.setHeader("Content-type", "application/json;charset=UTF-8"); post.setHeader("Accept", "application/json;charset=UTF-8"); post.setEntity(new StringEntity(params, Consts.UTF_8)); response = httpClient.execute(post); resResult = EntityUtils.toString(response.getEntity(), "utf-8"); logger.info("result = {}", resResult); JSONObject jsonObject = JSONObject.parseObject(resResult); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return ResultUtil.success(jsonObject); } else { return ResultUtil.error(500, "接口异常!", JSONObject.parse(resResult)); } } catch (Exception e) { e.printStackTrace(); return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult)); } finally { httpClient.close(); } } @SneakyThrows public static PageResult> doGetJson(String url, String params) { logger.info("参数信息 = {}", params); logger.info("请求地址 = {}", url); httpClient(); CloseableHttpResponse response = null; String resResult = ""; try { String urlBuilder = constructionParams(url, params); HttpGet get = new HttpGet(urlBuilder); get.setHeader("Content-type", "application/json;charset=UTF-8"); get.setHeader("Accept", "application/json;charset=UTF-8"); response = httpClient.execute(get); resResult = EntityUtils.toString(response.getEntity(), "utf-8"); logger.info("result = {}", resResult); JSONObject jsonObject = JSONObject.parseObject(resResult); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return ResultUtil.success(jsonObject); } else { return ResultUtil.error(500, "接口异常!", jsonObject); } } catch (Exception e) { e.printStackTrace(); return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult)); } finally { httpClient.close(); } } @SneakyThrows public static PageResult> doPutJson(String url, String params) { logger.info("参数信息 = {}", params); logger.info("请求地址 = {}", url); httpClient(); CloseableHttpResponse response; String resResult; try { HttpPut put = new HttpPut(url); put.setHeader("Content-type", "application/json;charset=UTF-8"); put.setHeader("Accept", "application/json;charset=UTF-8"); put.setEntity(new StringEntity(params, Consts.UTF_8)); response = httpClient.execute(put); resResult = EntityUtils.toString(response.getEntity(), "utf-8"); logger.info("result = {}", resResult); JSONObject jsonObject = JSONObject.parseObject(resResult); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return ResultUtil.success(jsonObject); } else { return ResultUtil.error(500, "接口异常!", JSONObject.parse(resResult)); } } catch (Exception e) { logger.info("方法异常{}", e.getMessage()); return ResultUtil.error(); } finally { httpClient.close(); } } @SneakyThrows public static PageResult> doPutText(String url, String params) { logger.info("参数信息 = {}", params); logger.info("请求地址 = {}", url); httpClient(); CloseableHttpResponse response; String resResult; try { HttpPut put = new HttpPut(url); put.setEntity(new StringEntity(params, Consts.UTF_8)); response = httpClient.execute(put); resResult = EntityUtils.toString(response.getEntity(), "utf-8"); logger.info("result = {}", resResult); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return ResultUtil.success(resResult); } else { return ResultUtil.error(500, "接口异常!", resResult); } } catch (Exception e) { logger.info("方法异常{}", e.getMessage()); return ResultUtil.error(); } finally { httpClient.close(); } } @SneakyThrows public static PageResultdoDeleteJson(String url, String params) { logger.info("url == {}", url); logger.info("params == {}", params); httpClient(); CloseableHttpResponse response; String resResult; try { String urlBuilder = constructionParams(url, params); HttpDelete delete = new HttpDelete(urlBuilder); delete.setHeader("Content-type", "application/json;charset=UTF-8"); delete.setHeader("Accept", "application/json;charset=UTF-8"); response = httpClient.execute(delete); logger.info("DELETE 返回状态:" + response.getStatusLine()); resResult = EntityUtils.toString(response.getEntity()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { logger.info("Request successfully executed"); return ResultUtil.success(JSONObject.parseObject(resResult)); } else { return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult)); } } catch (Exception e) { return ResultUtil.error(); } finally { httpClient.close(); } } @SneakyThrows public static PageResult doPostXml(String url, String params, File file, String fileParamName) { logger.info("url == {}", url); logger.info("params == {}", params); httpClient(); CloseableHttpResponse response; try { HttpPost post = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (null != file) { builder.addBinaryBody( fileParamName, new FileInputStream(file), ContentType.APPLICATION_XML, file.getName()); } if (Strings.isNotBlank(params)) { JSONObject paramsObject = JSONObject.parseObject(params); Iterator > iterator = paramsObject.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); String key = entry.getKey(); Object value = entry.getValue(); builder.addTextBody(key, String.valueOf(value), ContentType.TEXT_PLAIN); } } HttpEntity multipart = builder.build(); post.setHeader("Accept", "application/xml;charset=UTF-8"); post.setEntity(multipart); response = httpClient.execute(post); logger.info("POST 返回状态:" + response.getStatusLine()); String resResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { logger.info("Request successfully executed"); return ResultUtil.success(resResult); } else { return ResultUtil.error(500, "接口异常", resResult); } } catch (Exception e) { e.printStackTrace(); return ResultUtil.error(); } finally { httpClient.close(); } } @SneakyThrows public static PageResult doPutFormData(String url, String params) { return doPutFormData(url, params, null, ""); } @SneakyThrows public static PageResult doPutFormData(String url, String params, File file, String fileParamName) { logger.info("url == {}", url); logger.info("params == {}", params); httpClient(); CloseableHttpResponse response = null; String resResult = ""; try { HttpPut put = new HttpPut(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (file != null) { builder.addBinaryBody( fileParamName, new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, file.getName()); } if (Strings.isNotBlank(params)) { JSONObject paramsObject = JSONObject.parseObject(params); Iterator > iterator = paramsObject.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); String key = entry.getKey(); Object value = entry.getValue(); builder.addTextBody(key, String.valueOf(value), ContentType.TEXT_PLAIN); } } HttpEntity multipart = builder.build(); put.setHeader("Accept", "application/json;charset=UTF-8"); put.setEntity(multipart); response = httpClient.execute(put); logger.info("PUT 返回状态:" + response.getStatusLine()); resResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { logger.info("Request successfully executed"); return ResultUtil.success(JSONObject.parseObject(resResult)); } else { return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult)); } } catch (Exception e) { e.printStackTrace(); return ResultUtil.error(); } finally { httpClient.close(); } } private static String constructionParams(String url, String params) { StringBuilder urlBuilder = new StringBuilder(url); if (!"".equals(params)) { JSONObject paramObject = JSONObject.parseObject(params); Iterator > iterator = paramObject.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry next = iterator.next(); String key = next.getKey(); String valueOf = String.valueOf(next.getValue()); String param = "&" + key + "=" + valueOf; urlBuilder.append(param); } } return urlBuilder.toString(); } public static String getIsApiUrl(String ip, Integer port) { return PREFIX + "://" + ip + ":" + port; }}
关键词:
全球热讯:java HttpClient工具类
1万4千条生活小知识常识大全ACCESS\EXCEL数据库
要闻速递:【财经分析】短端利率定价基本合理 机构提示关注调整风险
世界新动态:开展12600余项减排项目 广东持续打好臭氧污染防治攻坚战
惠誉下调美国不动产相关产业评级展望至恶化 滚动
当前速讯:2023西安钟南山南五台景区高考免费活动
广东一考生着急进考场跑掉洞洞鞋:焦急光脚跑向考场_天天视点
高考时间为何定在6月?少数人能猜到 天天新消息
国产替代重大进步!华为100%自研数据库亮相 中国金融云第一
【天天快播报】AirPower“精神续作”?苹果新iPad专利塞满磁性线圈
上市不到1个月 要打比亚迪宋的哈弗枭龙系列有优惠了:立省6000块!
警用无人机空中巡飞护航高考
凌玮科技:6月6日融资买入132.66万元,融资融券余额4331.19万元
环球最新:我国部署实施2023年公海自主休渔措施
【全球快播报】香港警方国安处拘捕6人 其中2人涉嫌危害国家安全
北京城区供水已超去年最高日供水量 夏季高峰供水保障开启
C++ 友元函数-环球看点
GRPC核心概念、架构和生命周期
漳州市应急管理综合执法支队准执法保安全 护航企业促发展_每日动态
世界快资讯丨国内首个全栈自主数据库!华为云GaussDB迈出关键一步
今日快看!《敢死队4》新海报公布:杰森·斯坦森变男主!
飞凡巴赫座舱来了:全球首创主动式座椅 可自动充气放气
国内唯一!华为推出首款全栈自主数据库GaussDB:改变游戏规则
2499元起 荣耀90系列首销:全系2亿像素写真相机-世界报资讯
河北衡水一老师用2023根空笔芯打造“梦想之舟”祝福考生
余化敏调研城区集中供热项目建设 天天消息
生活诗和远方出自哪里_诗和远方出自哪里 环球新资讯
SRC赏金猎人—笔记一|每日短讯
springBoot自动装配机制
天天看点:盐系男友是什么意思_盐系少年什么意思都有些啥特点
环球信息:亿纬锂能:融资净买入1292.67万元,融资余额29.58亿元(06-06)
世界短讯!6月6日醋酐产业链价格汇总
快看:6月6日高平化工糠醇价格平稳
俄媒:卡霍夫卡大坝已坍塌近半_下游一城市水位上涨超12米
开园7年涨价4次 专家称国内建第三座迪士尼概率不大
可能是3K价位最高颜值!七彩虹iGame RTX 4060 Ti Ultra W OC 8GB评测:性能不弱于RTX 3070|世界热闻
五菱缤果减配ESC、自动驻车被投诉 车主:看海鸥卖的好了才加上 环球观速讯
世界观天下!高通骁龙8 Gen3曝光:X4超大核主频达3.7GHz 史无前例
高考首日 衡水中学高考生6点跑操:已持续数年|全球今头条
幽默小笑话大全爆笑段子_幽默小笑话大全爆笑-世界热头条
网络语不感冒是什么意思 对某人某事不太感冒是啥意思
通行宝:融资净偿还130.68万元,融资余额3646.21万元(06-06)
【环球新视野】新乡市政务服务“跨省通办”合作再添伙伴
全球视点!三天吃透Spring面试八股文
健康食物功效大全ACCESS数据库
SUID~这账怎么算?|全球快讯
魔兽世界萨尔玛在哪(wow怀旧服探索地狱火半岛成就萨尔玛位置坐标)
底层架构大改 微软Win12明年发布:英特尔AMD已做好准备 环球微动态
华为发布全球首款800GE数据中心核心交换机:支持288个800GE端口_世界新资讯
【焦点热闻】国产带头杀价 4TB SSD干到999元 PCIe 4.0硬盘首次成为主流
【快播报】江西鸭脖事件再升级!胡锡进:市监局有必要进行更加清晰的拍摄,并公之于众
安德烈·彼得莱乌
ALCO HOLDINGS(00328):资本重组已生效-即时看
天天简讯:56岁黎明素颜近照曝光,与粉丝互动接地气,冻龄容颜令人震惊
国际油价持续走低-天天时讯
世界百事通!迅雷(XNET.US)盘前一度涨超25%! 董事会批准2000万美元股票回购计划
热点!福建省三明市2023-06-04 20:41发布暴雨红色预警
微控制器实时操作系统实践2了解RTOS任务_环球微资讯
当前看点!呼伦贝尔草原上发现了千年前的岩画→
什么是房颤手术_什么是房颤
通讯!聚焦补链强链 抢抓“招商”“落地”
世界百事通!【读财报】5月上市公司定增动态:实际募资200.65亿元 北汽蓝谷和山西焦煤募资额居前
头条:新华全媒+丨七项签约!长三角生态共治再扩“新版图”
乳房一个大一个小正常吗?_乳房一个大一个小正常吗
估值超过2000亿 OpenAI暂无上市计划 :不想被资本裹挟-全球滚动
波音787“梦想客机”发现新缺陷:或推迟交付
天天最新:正面硬刚骁龙!天玑9300规格出炉:史无前例的全大核架构
观热点:6月9日上映!《变形金刚7》终极预告发布:高考完必看大片
考生人数再创历史新高!直击2023高考现场 南京夫子庙挤满为高考祈福的人 新动态
免疫球蛋白多少钱一针_打狂犬疫苗一针比一针疼吗_世界观焦点
世界观察:大比兜子啥意思是哪里的方言 大逼斗是什么意思
石门宝峰街道:彻底清扫营商环境领域顽障痼疾|环球微头条
全球消息!安德森短篇小说选
读数据压缩入门笔记04_统计编码|天天观点
2018款速腾钥匙图片 新速腾有几把钥匙? 世界速看
派瑞股份:公司深耕于特(超)高压直流输电领域 主要产品属于特高压直流工程中换流阀用核心器件
切了佛南昌话什么意思_秋婆梨南昌话什么意思|简讯
每日快播:2023高考加油!广东明确停课不停考:注意事项一定要了解
【天天新视野】伴娘堵门要红包被伴郎连人带门踹飞 新娘淡定看一切:隔着屏幕都感到疼
当前关注:固定资产盘盈盘亏计入固定资产清理吗_固定资产盘盈盘亏计入
金价持续反弹,后市能否大涨?GMA天选指标人PK赛“赛况”激烈,指标学员连续霸占双榜首3天,盈利近10w美元,今天即将翻仓?点击查下最新排行榜>>> 天天快资讯
网络语十一路公交车啥意思 十一路公交车是什么梗
安德森溪蟹 天天观天下
天天热门:美团太狠:接口被恶刷10Wqps,怎么防?
环球微动态丨文心一言 VS 讯飞星火 VS chatgpt (33)-- 算法导论5.2 5题
环球快资讯丨微信dat文件转图片(jpg,png,gif)
敢情是什么意思?_敢情是什么意思方言那敢情好啊是什么意思
甲苯与氯气在光照下反应主要生成一氯代物_甲苯与氯气在光照下反应主要生成 最资讯
实时:硅料价格连续四周降幅超10%机构:判断供应链将进入负反馈阶段
精选!录制宏功能为7×50+5要怎么录制_录制宏是什么意思
诗经国风卫风木瓜_卫风木瓜
每日快播:刚赚钱就全国9.9元 瑞幸哪来的勇气?
家长网友建议高考期间高铁降速 官方回应:不行
焦点热文:14万元的比亚迪在海外乱杀 比国内贵十几万依然销量第一
侵犯特斯拉名誉权败诉后博主拒不道歉 陶琳无奈发文
再次对接天舟五号:中国空间站空前庞大!
焦点速讯:苹果查看电池充电次数快捷指令
美股异动丨Coinbase大跌20% 被SEC起诉违反美国证券法
Xiaomi 12 Pro影像_天天热消息
中庸之道的理论基础是_中庸之道的理论基础