java 设置 Spring RestTemplate 的默认内容类型标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43590448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set default content type header of Spring RestTemplate
提问by Rlarroque
I'm currently using an OAuth2RestOperations that extends the Spring RestTemplate and I would like to specify the content type header.
我目前正在使用扩展 Spring RestTemplate 的 OAuth2RestOperations,我想指定内容类型标头。
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.
但如果能够在 bean 初始化期间一劳永逸地设置它,并且直接使用 getforObject 方法而不是交换方法,那实际上会很棒。
回答by diginoise
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.
RestTemplate
如果您的应用程序中有一些其他专门的或通用的 REST 模板,您可以子类化。
回答by maaw
If you're using Spring Boot, you can just
如果您使用的是 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;
}
}