Set default content type header of Spring RestTemplate

First you have to create request interceptor:

public class JsonMimeReqInterceptor implements ClientHttpRequestInterceptor {

  @Override
  public ClientHttpResponse intercept(HttpRequest request, byte[] body,
        ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add("Accept", MediaType.APPLICATION_JSON);
    return execution.execute(request, body);
  }
}

... and then you have rest template creation code which uses above interceptor:

@Configuration
public class MyAppConfig {

  @Bean
  public RestTemplate restTemplate() {
      RestTemplate template = new RestTemplate(clientHttpRequestFactory());
      //magic happens below:
      template.setInterceptors(Collections.singletonList(new JsonMimeReqInterceptor()));
      return restTemplate;
  }
}

You could subclass RestTemplate if you were to have some other specialised or universal REST templates in your application.


Since Spring Boot 1.4 you can use the RestTemplateBuilder

RestTemplate restTemplate = new RestTemplateBuilder()
            .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
            .build();

If you're using Spring Boot, you can just

@Configuration
    public class RestConfig {
        @Bean
        public RestTemplate getRestTemplate() {
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.setInterceptors(Collections.singletonList(new HttpHeaderInterceptor("Accept",
                    MediaType.APPLICATION_JSON.toString())));
            return restTemplate;
        }
    }

Tags:

Java

Spring