增加interceptor
public static class UserAgentInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpHeaders headers = request.getHeaders();
headers.add(HttpHeaders.USER_AGENT, "your agent");
return execution.execute(request, body);
}
}
设置interceptor
@Bean
public RestTemplate restTemplate() {
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(CONN_TIMEOUT_IN_MILLIS);
httpRequestFactory.setConnectTimeout(CONN_TIMEOUT_IN_MILLIS);
httpRequestFactory.setReadTimeout(READ_TIMEOUT_IN_MILLIS);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
restTemplate.setInterceptors(Collections.singletonList(new UserAgentInterceptor()));
return restTemplate;
}