发送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;
    }
}
相关推荐
Hvitur2 分钟前
eclipse新建SpringBoot项目
java·spring boot·eclipse
Nandeska12 分钟前
6、认识和使用Redis Stack
java·数据库·redis
J2虾虾36 分钟前
Springboot项目中循环依赖的问题
java·开发语言
weixin_7042660538 分钟前
事务管理全解析:从ACID到Spring实现
java·数据库·spring
Barkamin42 分钟前
冒泡排序的简单实现
java·算法·排序算法
熙胤1 小时前
springboot与springcloud对应版本
java·spring boot·spring cloud
J2虾虾1 小时前
SpringBoot 中给 @Autowired 搭配 @Lazy
java·spring boot·后端
皙然1 小时前
深入理解 Java HashSet
java·开发语言
摇滚侠1 小时前
Java 项目教程《黑马商城-ElasticSearch 篇》,分布式架构项目,从开发到部署
java·分布式·elasticsearch
佩奇大王1 小时前
P2408 特殊日期
java·开发语言