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

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

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

调用方式

java 复制代码
@Autowired
private HttpServletRequest request;

先注入HttpServletRequest


public xxx xxx(){
    String url = "http://" + ip +":8082/inAndOut/into/xxxxxx";
    String userCode = request.getHeader("usercode");

    //动态传递Header中的userCode,用来给组件服务接口传userCode
    Map<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中测试

工具类

java 复制代码
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;
    }
}
相关推荐
小碗羊肉14 分钟前
【JavaWeb | 第五篇】JDBC
java·开发语言·数据库
江南十四行28 分钟前
Python上下文管理器与with语句——资源管理的艺术
java·jvm·数据库
书源丶29 分钟前
四十五、函数式接口与 Lambda 表达式
java·开发语言
直奔標竿30 分钟前
MySQL与Redis数据一致性实战方案(避坑指南)
java·数据库·spring boot·redis·mysql·spring·缓存
java1234_小锋32 分钟前
Java进程突然挂了如何排查?
java·开发语言
夕除36 分钟前
spring boot--04
java·spring boot
java小白小1 小时前
Guava Cache 本地缓存
java
梦梦代码精1 小时前
LikeShop 二次开发扩展能力白皮书——面向业务增长的可扩展电商架构实践
java·架构·github
极客先躯1 小时前
高级java每日一道面试题-2025年12月05日-实战篇[Dockerj]-Docker 安装后的默认存储路径是什么?如何修改?
java·docker·默认存储路径在不同系统上的区别·linux overlay2·修改存储路径的理论方法·修改流程中的关键理论点
祁_z1 小时前
LangSmith 实操指南「Agent 可观测性系统」
java·服务器