发送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;
    }
}
相关推荐
许彰午2 分钟前
03_Java流程控制详解
java·开发语言·python
霍格沃兹测试学院-小舟畅学7 分钟前
接口自动化测试的下一个十年:从脚本到Skills,让AI学会“如何测”
java·前端·人工智能
我命由我1234510 分钟前
Retrofit - URL 格式错误问题、支持 HTTP 与 HTTPS
java·http·https·java-ee·android studio·android-studio·retrofit
灰灰老师13 分钟前
Docker部署Tomcat9
java·linux·docker·tomcat
西安邮电大学14 分钟前
Kafka如何避免重复消费
java·后端·其他·面试·kafka
ppandss116 分钟前
JavaWeb从0到1-DAY11-MyBatis入门
java·tomcat·mybatis
闪电悠米19 分钟前
黑马点评-优惠券秒杀-03_basic_seckill_and_oversell
java·数据库·spring boot·spring·缓存·oracle·面试
兰令水20 分钟前
leecodecode【双指针题2】【2026.5.26打卡-java版本】
java·开发语言·算法
ch.ju21 分钟前
Java程序设计(第3版)第四章——引用
java·开发语言