一、添加拦截器
public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor { private final String headerName; private final String headerValue; public HeaderRequestInterceptor(String headerName, String headerValue) { this.headerName = headerName; this.headerValue = headerValue; } @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { request.getHeaders().set(headerName, headerValue); return execution.execute(request, body); } }
二、RestTemplate Bean
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(new HeaderRequestInterceptor("token", "123")); RestTemplate restTemplate = new RestTemplate(); restTemplate.setInterceptors(interceptors); return restTemplate; } }
三、使用
@Autowired private RestTemplate restTemplate;
原文链接:https://www.cnblogs.com/victorbu/p/12708340.html