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

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

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

调用方式

@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中测试

工具类

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java发送HTTP POST请求非常常见和简单,可以使用HttpURLConnection或HttpClient来实现。获取返回的请求头header也很简单,只需要在发送请求后使用getResponseHeader()或getAllHeaders()方法获取即可。 以HttpURLConnection为例,发送POST请求并获取返回的请求头header的代码如下: ``` URL url = new URL("http://www.example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(jsonString.getBytes()); os.flush(); // 获取返回的请求头header Map<String, List<String>> headers = conn.getHeaderFields(); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String key = entry.getKey(); List<String> values = entry.getValue(); System.out.println(key + ": " + values); } BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); os.close(); conn.disconnect(); ``` 上述代码中,首先创建了一个URL和HttpURLConnection对象,然后设置POST请求的Content-Type,将请求体写入输出流中,并发送请求。接着使用conn.getHeaderFields()方法获取返回的请求头header并遍历输出。最后读取返回的响应体并关闭连接。 需要注意的是,如果返回的响应头中有多个值,则可以用getList()方法获取并输出。此外,如果需要在请求头中添加自定义的header,则可以使用setRequestProperty()方法来实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值