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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:31:32  来源:igfitidea点击:

Is there a way to pass header information in Spring RestTemplate DELETE call

javaspringweb-servicesrestresttemplate

提问by Zeeshan

In Spring RestTemplatewe 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 DELETErequest with header information?

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

回答by David Lavender

You can use the exchangemethod (which takes any HTTP request type), rather than using the deletemethod:

您可以使用该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 ClientHttpRequestInterceptorand 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(...)