设置Spring RestTemplate的默认内容类型标头 [英] Set default content type header of 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屋!