Set default content type header of Spring RestTemplate

前端 未结 2 879
被撕碎了的回忆
被撕碎了的回忆 2021-02-18 23:55

I\'m currently using an OAuth2RestOperations that extends the Spring RestTemplate and I would like to specify the content type header.

The only thing I\'ve managed to do

相关标签:
2条回答
  • 2021-02-19 00:28

    First you have to create request interceptor:

    public class JsonMimeInterceptor 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 restTemplate = new RestTemplate(clientHttpRequestFactory());
          restTemplate.setInterceptors(Collections.singletonList(new JsonMimeInterceptor()));
          return restTemplate;
      }
    }
    

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

    0 讨论(0)
  • 2021-02-19 00:30

    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;
            }
        }
    
    0 讨论(0)
提交回复
热议问题