RestTemplate如何配置调用接口的请求头呢?
下文笔者讲述RestTemplate调用接口时,配置请求头的方法及示例分享
我们都知道RestTemplate默认调用时,
不会携带请求头,如果我们需要携带请求头,则必须进行额外配置
那么如何配置RestTempate调用请求头呢?下文笔者将一一道来,如下所示
RestTemplate携带请求头的实现思路
方式一: 在每次发送请求时 构建一个HttpEntity对象 传入请求参数与请求头 方式二: 通过配置RestTemplate 使使用RestTemplate调用的http请求都携带上请求头例
方式一
每次发送请求时
构建一个HttpEntity对象
传入请求参数和请求头
以下是通过postForObject为例实现
@GetMapping("/test")
public Map<String, Object> getBlobMetadatalist(){
// 构建你的请求头
HttpHeaders headers = new HttpHeaders();
headers.set("token","************************");
headers.set("Content-Type", "application/json");
// 构建你的请求体参数
HashMap<String, String> map = HashMap<>();
map.put("yourParma", "youValue");
// 组合请求头与请求体参数
HttpEntity<String> requestEntity = new HttpEntity<>(JSONObject.toJSONString(map), headers);
// path -> 请求地址,requestEntity -> 请求参数相关对象,HashMap.class -> 返回结果映射类型
return restTemplate.postForObject(path, requestEntity, HashMap.class);
}
方式二
配置RestTemplate
使用RestTemplate调用的http请求都携带上请求头
/**
* RestTemplate配置类
*/
@Slf4j
@Configuration
public class RestTemplateConfig {
/**
* 常用远程调用RestTemplate
* @return restTemplate
*/
@Bean("restTemplate")
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate();
// 设置通用的请求头
HeaderRequestInterceptor myHeader = new HeaderRequestInterceptor("token", "**********");
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(myHeader);
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
/**
* 拦截器类
* restTemplatep后续调用请求时携带请求头
*/
public static class HeaderRequestInterceptor implements ClientHttpRequestInterceptor{
private final String header;
private final String value;
public HeaderRequestInterceptor(String header, String value){
this.header = header;
this.value = value;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().set(header, value);
return execution.execute(request, body);
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


