Set default content type header of Spring RestTemp

2020-07-01 17:56发布

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 was to explicitly set my header during the request:

public String getResult() {
    String result = myRestTemplate.exchange(uri, HttpMethod.GET, generateJsonHeader(), String.class).getBody();
}

private HttpEntity<String> generateJsonHeader() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    return new HttpEntity<>("parameters", headers);
}

But it would actually be great to be able to set that once and for all during the bean initialization, and directly use the getforObject method instead of exchange.

标签: java spring
2条回答
女痞
2楼-- · 2020-07-01 18:34

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;
        }
    }
查看更多
够拽才男人
3楼-- · 2020-07-01 18:54

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.

查看更多
登录 后发表回答