java 有没有办法在 Spring RestTemplate DELETE 调用中传递标头信息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30123021/
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
Is there a way to pass header information in Spring RestTemplate DELETE call
提问by Zeeshan
In Spring RestTemplate
we are having the following methods for delete.
在 Spring 中,RestTemplate
我们有以下删除方法。
@Override
public void delete(String url, Object... urlVariables) throws RestClientException {
execute(url, HttpMethod.DELETE, null, null, urlVariables);
}
@Override
public void delete(String url, Map<String, ?> urlVariables) throws RestClientException {
execute(url, HttpMethod.DELETE, null, null, urlVariables);
}
@Override
public void delete(URI url) throws RestClientException {
execute(url, HttpMethod.DELETE, null, null);
}
None of these methods are having any place to pass header information. Is there any other method which can be used for DELETE
request with header information?
这些方法都没有任何地方可以传递标头信息。有没有其他方法可以用于DELETE
带有标头信息的请求?
回答by David Lavender
You can use the exchange
method (which takes any HTTP request type), rather than using the delete
method:
您可以使用该exchange
方法(它采用任何 HTTP 请求类型),而不是使用该delete
方法:
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("X-XSRF-HEADER", "BlahBlah");
headers.add("Authorization", "Basic " + blahblah);
etc...
HttpEntity<?> request = new HttpEntity<Object>(headers);
restTemplate.exchange(url, HttpMethod.DELETE, request, String.class);
回答by jny
You can implement ClientHttpRequestInterceptor
and set it for your restTemplate
. In your interceptor:
您可以ClientHttpRequestInterceptor
为您的restTemplate
. 在您的拦截器中:
@Override
public ClientHttpResponse intercept(
HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
if (request.getMethod() == HttpMethod.DELETE){
request.getHeaders().add(headerName, headerValue);
}
return execution.execute(request, body);
}
}
In your config:
在您的配置中:
restTemplate.setInterceptors(...)