有没有办法在Spring RestTemplate DELETE调用中传递头信息

时间:2015-05-08 11:44:32

标签: java spring web-services rest resttemplate

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

这些方法都没有任何传递标题信息的地方。是否有任何其他方法可以用于带有标题信息的DELETE请求?

2 个答案:

答案 0 :(得分:19)

您可以使用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);

答案 1 :(得分:5)

您可以实施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);
        }
}

在你的配置中:

restTemplate.setInterceptors(...)