【问题标题】:Set default content type header of Spring RestTemplate设置 Spring RestTemplate 的默认内容类型标头
【发布时间】:2017-04-24 14:12:52
【问题描述】:

我目前正在使用扩展 Spring RestTemplate 的 OAuth2RestOperations,我想指定内容类型标头。

我唯一能做的就是在请求期间明确设置我的标头:

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);
}

但如果能够在 bean 初始化期间一劳永逸地设置它,并且直接使用 getforObject 方法而不是交换,那实际上会很棒。

【问题讨论】:

    标签: java spring


    【解决方案1】:

    首先你必须创建请求拦截器:

    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);
      }
    }
    

    ...然后你就有了使用上述拦截器的其余模板创建代码:

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

    如果您的应用程序中有一些其他专用或通用 REST 模板,您可以继承 RestTemplate

    【讨论】:

    • 感谢您的回答。在我的拦截器中,我添加了这两行: headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON);
    • 我不确定这是正确的解决方案。例如。 Content-Type 标头(例如控制编码)在 ClientHttpRequestInterceptor 被调用之前使用,这对我来说是编码问题。有其他人观察到这种行为吗?
    【解决方案2】:

    如果你使用的是 Spring Boot,你可以

    @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;
            }
        }
    

    【讨论】:

    • 最近春天引入了“HttpHeaderInterceptor”吗?我正在使用 spring boot 2.0.1.RELEASE 并没有找到它。可能是我对这个类没有正确的依赖
    • @AshharJawaid 根据 Javadoc 它是在 Spring Boot 1.3.0 中引入的
    • 它在 devtools 中,所以不适合生产使用
    【解决方案3】:

    从 Spring Boot 1.4 开始,您可以使用 RestTemplateBuilder

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

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 2022-11-03
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      相关资源
      最近更新 更多