发送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;
    }
}
相关推荐
拾贰_C9 分钟前
【SpringBoot】MyBatisPlus(MP | 分页查询操作
java·spring boot·后端·spring·maven·apache·intellij-idea
猛踹瘸子那条好腿の13 分钟前
Spring-boot初次使用
java·springboot
我不是程序猿儿2 小时前
【C#】 lock 关键字
java·开发语言·c#
tmacfrank3 小时前
网络编程中的直接内存与零拷贝
java·linux·网络
weixin_472339464 小时前
Maven 下载安装与配置教程
java·maven
Magnum Lehar5 小时前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
就叫飞六吧5 小时前
Spring Security 集成指南:避免 CORS 跨域问题
java·后端·spring
Mcworld8575 小时前
java集合
java·开发语言·windows
天黑请闭眼5 小时前
IDEA:程序编译报错:java: Compilation failed: internal java compiler error
java·intellij-idea
苍煜6 小时前
Maven构建流程详解:如何正确管理微服务间的依赖关系-当依赖的模块更新后,我应该如何重新构建主项目
java·微服务·maven