当前位置: 首页 > news >正文

Java 请求头加header

Java 请求头加header


通常情况下,java的http请求接口可以无需加header,但也有的第三方接口强制要求将accesstoken放在请求头中,而不能作为普通参数传递,这样就需要在请求头中加header,这里写了几个http请求工具类的方法,希望对大家有帮助

/*** @Description 可以添加headers 的请求工具类* @Author P001* @Date 2023/3/3 15:06* @Version 1.0*/public class HttpUtilsV2 {private static final CloseableHttpClient httpclient = HttpClients.createDefault();private static final Logger log = LoggerFactory.getLogger(HttpUtilsV2.class);private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";/*** 发送HttpGet请求** @param url   url* @param param param* @return 返回字符串*/public static String sendGet(String url, String param, Map<String,String> headers) {String result = null;CloseableHttpResponse response = null;try {String urlNameString = url + "?" + param;log.info("sendGet - {}", urlNameString);HttpGet httpGet = new HttpGet(urlNameString);httpGet.setHeader("User-Agent", userAgent);if (Objects.nonNull(headers)) {Set<Map.Entry<String, String>> entries = headers.entrySet();if (CollectionUtils.isNotEmpty(entries)) {for (Map.Entry<String, String> entry : entries) {httpGet.setHeader(entry.getKey(), entry.getValue());}}}response = httpclient.execute(httpGet);HttpEntity entity = response.getEntity();if (entity != null) {result = EntityUtils.toString(entity);}} catch (Exception e) {log.error(e.getMessage());} finally {if (response != null) {try {response.close();} catch (IOException e) {log.error(e.getMessage());}}}return result;}/*** 发送HttpGet请求* 如果使用此方法,记得在finally中关闭response* @param url   url* @return 返回字符串*/public static CloseableHttpResponse sendGet(String url) {CloseableHttpResponse response = null;try {log.info("sendGet - {}", url);HttpGet httpGet = new HttpGet(url);response = httpclient.execute(httpGet);} catch (Exception e) {log.error(e.getMessage());}return response;}/*** 发送HttpPost请求** @param url     url* @param jsonStr 入参* @return 返回字符串*/public static String sendPost(String url, String jsonStr) {String result = null;// 字符串编码StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);// 设置content-typeentity.setContentType("application/json");HttpPost httpPost = new HttpPost(url);// 防止被当成攻击添加的httpPost.setHeader("User-Agent", userAgent);// 接收参数设置httpPost.setHeader("Accept", "application/json");httpPost.setEntity(entity);CloseableHttpResponse response = null;try {response = httpclient.execute(httpPost);HttpEntity httpEntity = response.getEntity();result = EntityUtils.toString(httpEntity);} catch (IOException e) {log.error(e.getMessage());} finally {// 关闭CloseableHttpResponseif (response != null) {try {response.close();} catch (IOException e) {log.error(e.getMessage());}}}return result;}/*** 发送HttpPost请求** @param url url* @return 返回字符串*/public static String sendPost(String url) {String result = null;// 得到一个HttpPost对象HttpPost httpPost = new HttpPost(url);// 防止被当成攻击添加的httpPost.setHeader("User-Agent", userAgent);CloseableHttpResponse response = null;try {// 执行HttpPost请求,并得到一个CloseableHttpResponseresponse = httpclient.execute(httpPost);// 从CloseableHttpResponse中拿到HttpEntityHttpEntity entity = response.getEntity();// 将HttpEntity转换为字符串result = EntityUtils.toString(entity);} catch (IOException e) {log.error(e.getMessage());} finally {// 关闭CloseableHttpResponseif (response != null) {try {response.close();} catch (IOException e) {log.error(e.getMessage());}}}return result;}}

另外也可以基于当前请求工具类获取远程资源文件并下载到本地,比如资源路径:

https://kefu.test.com/store/func/imagetrans/image2.php?f=o7AyJtNijflDAP1RHWeTarsltMgvRHX9Kg&amp;amp;q=+LcyJNcy3PxABvhVGmeSbaR45KcjXzSkYtemrW3XSgPEcmFV9cDIGhYjkw2ryK+hPHa29q1VhgYHJA4ckaNcT2dmIhHQSjBLJ9F0NHo

作为参数传入下方法即可将远程资源文件下载到本地临时文件夹,同时将本地临时文件夹内容读取上传至腾讯云COS

/*** 获取小能资源文件* @return*/@Overridepublic String getSourceFile(String url, Date date) {String key = null;InputStream instream = null;CloseableHttpResponse response = null;FileOutputStream out = null;String tmppath = null;try {response = HttpUtilsV2.sendGet(url);if (Objects.nonNull(response)) {HttpEntity entity = response.getEntity();//获取文件后缀名Header header = entity.getContentType();String value = header.getValue();int i = value.lastIndexOf("/");String ext = value.substring(i + 1);//文件存储路径Calendar calendar = Calendar.getInstance();calendar.setTime(date);int year = calendar.get(Calendar.YEAR);int month = calendar.get(Calendar.MONTH) + 1;int day = calendar.get(Calendar.DAY_OF_MONTH);String folderName = String.format("%s/%s/%s/%s/", ConstantConfig.path, year, month, day);Random random = new Random();String fileName = date.getTime()+ random.nextInt(100000)+"."+ext;//先下载到本地,然后再读取,上传到costmppath = ConstantConfig.tmpPath + fileName;//判断是否存在文件,不存在则新建File file = new File(ConstantConfig.tmpPath);if (!file.exists()) {file.mkdirs();}out = new FileOutputStream(tmppath);entity.writeTo(out);//再次读取上传到cosinstream = new FileInputStream(tmppath);key = folderName + fileName;CosClientUtil.uploadFileToCos(instream,key);}} catch (IOException e) {e.printStackTrace();}finally {try {if (instream != null) {instream.close();}if (response != null) {response.close();}if (out != null) {out.close();}if (tmppath != null) {new File(tmppath).delete();}} catch (IOException e) {e.printStackTrace();}}return key;}

当然也可以不经过下载到本地临时目录再上传的方式直接将远程资源文件上传到腾讯云COS

  /*** 获取小能资源文件* @return*/@Overridepublic String getSourceFile(String url, Date date) {String key = null;InputStream instream = null;HttpClient client = new HttpClient();GetMethod get = null;try {get = new GetMethod(url);int httpStatus = client.executeMethod(get);if (HttpStatus.OK.value() == httpStatus) {// 得到网络资源的字节数组,并写入文件byte[] result = get.getResponseBody();instream = new ByteArrayInputStream(result);org.apache.commons.httpclient.Header header = get.getResponseHeader("Content-Type");String value = header.getValue();int i = value.lastIndexOf("/");String ext = value.substring(i + 1);//文件存储路径Calendar calendar = Calendar.getInstance();calendar.setTime(date);int year = calendar.get(Calendar.YEAR);int month = calendar.get(Calendar.MONTH) + 1;int day = calendar.get(Calendar.DAY_OF_MONTH);String folderName = String.format("%s/%s/%s/%s/", ConstantConfig.path, year, month, day);Random random = new Random();String fileName = date.getTime()+ random.nextInt(100000)+"."+ext;key = folderName + fileName;CosClientUtil.uploadFileToCos(instream,key);}} catch (IOException e) {e.printStackTrace();}finally {try {if (instream != null) {instream.close();}if (get != null) {get.releaseConnection();}client.getHttpConnectionManager().closeIdleConnections(0);} catch (IOException e) {e.printStackTrace();}}return key;}

相关文章:

  • Kubernetes 二进制安装
  • LeetCode322.零钱兑换
  • 结构体(c++语言)
  • PDF分页处理:技术与实践
  • 千益畅行,共享旅游卡,满足您多样化的同行出行需求
  • Web考试前端等级:深度剖析与实战攻略
  • 搭建python虚拟环境,并在VSCode中使用
  • 让你的TypeScript代码更优雅,这10个特性你需要了解下
  • htb-linux-9-sense
  • Web安全:Web体系架构存在的安全问题和解决方案
  • Debian13将正式切换到基于内存的临时文件系统
  • 中电金信:产教联合共育人才 AFAC2024金融智能创新大赛启动
  • k8s之deployments相关操作
  • 【图 - 遍历(BFS DFS)】深度优先搜索算法(Depth First Search), 广度优先搜索算法(Breadth First Search)
  • (佳作)两轮平衡小车(原理图、PCB、程序源码、BOM等)
  • 0x05 Python数据分析,Anaconda八斩刀
  • gcc介绍及安装
  • Java 内存分配及垃圾回收机制初探
  • Vue--数据传输
  • 从0搭建SpringBoot的HelloWorld -- Java版本
  • 来,膜拜下android roadmap,强大的执行力
  • 前嗅ForeSpider教程:创建模板
  • 小程序01:wepy框架整合iview webapp UI
  • AI算硅基生命吗,为什么?
  • Android开发者必备:推荐一款助力开发的开源APP
  • ​软考-高级-信息系统项目管理师教程 第四版【第23章-组织通用管理-思维导图】​
  • #define、const、typedef的差别
  • #pragma 指令
  • $(selector).each()和$.each()的区别
  • (2)关于RabbitMq 的 Topic Exchange 主题交换机
  • (4)事件处理——(2)在页面加载的时候执行任务(Performing tasks on page load)...
  • (附源码)计算机毕业设计高校学生选课系统
  • (三)c52学习之旅-点亮LED灯
  • (深入.Net平台的软件系统分层开发).第一章.上机练习.20170424
  • (顺序)容器的好伴侣 --- 容器适配器
  • (转)【Hibernate总结系列】使用举例
  • .mkp勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .net core 连接数据库,通过数据库生成Modell
  • .Net Web窗口页属性
  • .net 调用php,php 调用.net com组件 --
  • .net 简单实现MD5
  • @select 怎么写存储过程_你知道select语句和update语句分别是怎么执行的吗?
  • [ IOS ] iOS-控制器View的创建和生命周期
  • [ vulhub漏洞复现篇 ] ECShop 2.x / 3.x SQL注入/远程执行代码漏洞 xianzhi-2017-02-82239600
  • []使用 Tortoise SVN 创建 Externals 外部引用目录
  • [4]CUDA中的向量计算与并行通信模式
  • [Android] Amazon 的 android 音视频开发文档
  • [BZOJ4566][HAOI2016]找相同字符(SAM)
  • [C++]模板与STL简介
  • [fsevents@^2.1.2] optional install error: Package require os(darwin) not compatible with your platfo
  • [Google Guava] 2.1-不可变集合
  • [HNOI2008]玩具装箱toy
  • [Invalid postback or callback argument]昨晚调试程序时出现的问题,MARK一下
  • [Jquery] 实现温度计动画效果
  • [js]- 两个对象的合并(Object.assign)