Наше приложение вызывает другую службу отдыха, используя RestTemplate, это приложение Spring Boot. У меня есть требование, когда мне нужно скопировать свойство из заголовка http в тело запроса.
Выполнение этого вручную приведет к изменениям во многих местах. Я ищу универсальное решение, т. Е. Я мог бы расширить функциональность RestTemplate и использовать его во всем приложении.
Есть ли способ изменить RestTemplate для выполнения моих требований. Я уже рассмотрел возможности с помощью HttpMessageConverter, я могу добавить свойство Json, но ищу способ скопировать его из заголовка.
Пожалуйста, дайте мне знать, если я не совсем понимаю свои требования, любые указатели будут мне полезны.
Вы можете расширить поведение RestTemplate, реализовав ClientHttpRequestInterceptor
public class RestTemplateHeaderModifierInterceptor
implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(
HttpRequest request,
byte[] body,
ClientHttpRequestExecution execution) throws IOException {
ClientHttpResponse response = execution.execute(request, body);
response.getHeaders().add("Foo", "bar");
return response;
}
}
@Configuration
public class RestClientConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors
= restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<>();
}
interceptors.add(new RestTemplateHeaderModifierInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
}