The answer is mostly focused on @RicardoPieper's case, but the single RestTemplate
case (from OP) can still use this intercept based solution
In my opinion, it is best to be explicit, and not depend on the Content-Type
setting in any RestTemplate
. So set your header values for all calls like;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Post> entity = new HttpEntity<>(post, headers);
ResponseEntity<Post> response = someTemplate.postForEntity(uri, entity, Post.class);
But for your case, I came up with an idea, again doing the intercept solution but from a higher perspective (though it has an assumption still)
Have a listener for context refresh event;
@Component
public class MyListener implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private Map<String, RestTemplate> templates;
public void onApplicationEvent(ContextRefreshedEvent event) {
templates.entrySet().stream()
.filter(this::isJsonBased)
.map(Map.Entry::getValue)
.forEach(template -> template.setInterceptors(Collections.singletonList(new JsonMimeInterceptor())));
}
private boolean isJsonBased(Map.Entry<String, RestTemplate> entry) {
return entry.getKey().toLowerCase().contains("json");
}
}
Here I am getting all RestTemplate
beans in the context (with their bean names included, using the Map autowire feature), and doing a filter first, though this is the assumption part, I thought having "json"
in the name of the JSON
focused RestTemplate
beans, like;
@Bean
public RestTemplate jsonTemplate() {
return new RestTemplate();
}
and apply the intercept logic to all those beans.
public class JsonMimeInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpHeaders headers = request.getHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return execution.execute(request, body);
}
}
What do you think? =) It worked on my demo app, though there needs to be some way to distinguish between XML
based, and JSON
based RestTemplate
beans. If you can create such a distinction, you can add that logic in the isJsonBased()
method and still use this idea!