在Spring中, RestTemplate作为客户端向Restful API接口发送请求的工具类,通常需要对请求设置相似或者相同的Http Header(例如:spring cloud微服务内部接口调用,需要传递token)。每次请求之前都要通过HttpHeaders(实现MultiValueMap)/MultiValueMap(LinkedMultiValueMap)设置header信息并填入HttpEntity/RequestEntity(继承HttpEntity)中,这样十分麻烦。当然了强大的Spring总是有办法的,提供了ClientHttpRequestInterceptor接口,可以对请求进行拦截,在请求被发送至服务端之前修改其数据或是增强相应的信息。

Talk is cheap. Show me the code.

实现ClientHttpRequestInterceptor接口

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class TokenInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();

        //添加请求头信息(token)
        headers.add(HttpHeaders.AUTHORIZATION, String.format("%s %s", BEARER_TOKEN_TYPE, accessToken));
        // 请求继续被执行
        return execution.execute(request, body);
    }
}

配置RestTemplate自定义拦截器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@Configuration
public class RestTemplateConfig {
    @Autowired
    private TokenInterceptor tokenInterceptor;

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        //TokenInterceptor tokenInterceptor = new TokenInterceptor();
        restTemplate.setInterceptors(Collections.singletonList(tokenInterceptor));
        return restTemplate;
    }
}