背景
对接一个第三方接口,对方接口验证请求头必须带上Origin等于xxx,否则不会返回数据。当我们使用hutool的HttpUtil发送请求,抓包发现这个请求头没有带上,导致接口总是返回空数据
解决方案
使用okhttp client
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
OkHttpClient client = new OkHttpClient();
// 创建一个请求
Request.Builder builder = new Request.Builder().url("http://xxxx/v1/query/args");
Map<String, String> header = new HashMap<>();
header.put("Origin", "xxx");
header.put("Referer", "xxx");
header.put("User-Agent", "1");
if (CollUtil.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
builder.header(entry.getKey(), entry.getValue());
}
}
Request request = builder.build();
// 发起请求并获取响应
try (Response response = client.newCall(request).execute()) {
// 打印响应体的内容
return Objects.requireNonNull(response.body()).string();
} catch (Exception e) {
return "";
}
标签:Origin,xxx,Request,hutool,header,new,HttpUtil
From: https://www.cnblogs.com/ranger-dev/p/18525471