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

发送get请求并且发送请求头(header),java实现

发送get请求时,发送请求头(Header)中的内容

方便第二次调用其他url时传递参数,例如userCode或者租户编码

调用方式

@Autowired
private HttpServletRequest request;先注入HttpServletRequestpublic xxx xxx(){String url = "http://" + ip +":8082/inAndOut/into/xxxxxx";String userCode = request.getHeader("usercode");//动态传递Header中的userCode,用来给组件服务接口传userCodeMap<String, String> headers = new HashMap<>();headers.put("Content-Type", "application/json");headers.put("Authorization", "Bearer your_token_here");headers.put("tenantcode", tenantCode);headers.put("userCode", userCode);String request = HttpClientUtil.sendGetWithHeaders(url,headers);
}

userCode和tenantCode可以从Header中获取,前端也一样,这是在PostMan中测试

工具类

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import java.io.IOException;
import java.util.HashMap;
import java.util.Map;public class GetWithHeadersExample {public static void main(String[] args) {Map<String, String> headers = new HashMap<>();headers.put("Content-Type", "application/json");headers.put("Authorization", "Bearer your_token_here");String url = "http://example.com/api/endpoint";try {String response = sendGetWithHeaders(url, headers);System.out.println("Response: " + response);} catch (IOException e) {e.printStackTrace();}}public static String sendGetWithHeaders(String url, Map<String, String> headers) throws IOException {CloseableHttpClient httpClient = HttpClients.createDefault();HttpGet httpGet = new HttpGet(url);for (Map.Entry<String, String> entry : headers.entrySet()) {httpGet.addHeader(entry.getKey(), entry.getValue());}HttpResponse response = httpClient.execute(httpGet);HttpEntity entity = response.getEntity();String responseBody = EntityUtils.toString(entity);httpClient.close();return responseBody;}
}

http://www.lryc.cn/news/295014.html

相关文章:

  • 介绍docker
  • Web课程学习笔记--CSS盒模型
  • 中学一级教师是什么职称等级
  • 2024年2月CCF-全国精英算法大赛题目
  • arm 汇编积累
  • SpringBoot整理-安全(Spring Security)
  • 【技能树学习】Git入门——练习题解析
  • Springboot+vue的企业财务管理系统(有报告)。Javaee项目,springboot vue前后端分离项目
  • 手撕spring bean的加载过程
  • Linux系统中安装JDK
  • Stable Diffusion 模型下载:国风3 GuoFeng3
  • VUE项目导出excel
  • Springboot 整合 Elasticsearch(二):使用HTTP请求来操作ES
  • npm 淘宝镜像到期
  • 计算机网络——新型网络架构:SDN/NFV
  • 【精选】java继承进阶,子类继承父类(内存图、内存分析工具)
  • Google Play上架:因行为透明度被拒审或下架的政策自查(基于区块链的内容)
  • 备战蓝桥杯---搜索(剪枝)
  • ResizeObserver的使用
  • CleanMyMac X 4.14.7帮您安全清理Mac系统垃圾
  • C语言实现memcpy、memmove库函数
  • MySQL数据库④_表的约束(主键_自增长_唯一键_外键等)
  • SpringBoot过滤器获取请求的参数
  • 幻兽帕鲁mac可以玩吗?
  • webstorm、vscode、HBuilder配置eslint检查
  • 大数据知识图谱之深度学习——基于BERT+LSTM+CRF深度学习识别模型医疗知识图谱问答可视化系统
  • 年底个人总结
  • jsp教材管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目
  • SpringBoot:配置相关知识点
  • 在线JSON转SQL工具