RestTemplate运行时--如何添加请求头呢?
下文笔者讲述RestTemplate调用时--添加请求头的方法及示例分享,如下所示
创建HttpEntity对象,传入请求参数与请求头
通过RestTemplate调用的http请求都携带上请求头。
添加请求头的背景
由于一些请求时,需加入token 此时我们就需在RestTemplate请求时,放入token信息 那么RestTemplate如何实现这一需求呢?下文笔者将一一道来 如下所示
RestTemplate添加请求头的实现思路
方式1:
创建一个HttpEntity对象,并传入请求参数和请求头
方式2:
配置RestTemplate
通过RestTemplate调用http请求都携带上请求头
例:创建HttpEntity对象,传入请求参数与请求头
以下是通过postForObject为例实现
@GetMapping("/test")
public Map<String, Object> getBlobMetadatalist(){
// 构建你的请求头
HttpHeaders headers = new HttpHeaders();
headers.set("xxx","xxx");
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);
}
例2:配置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("xxx", "xxx");
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);
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


