设置Spring RestTemplate的默认内容类型标头 [英] Set default content type header of Spring RestTemplate

查看:3945
本文介绍了设置Spring RestTemplate的默认内容类型标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是,能够在bean初始化期间一劳永逸地设置该值,并直接使用getforObject方法而不是进行交换,实际上是很棒的.

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.

推荐答案

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

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

如果您的应用程序中需要其他一些专用或通用REST模板,则可以将RestTemplate子类化.

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

这篇关于设置Spring RestTemplate的默认内容类型标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆