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

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

在 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 这些方法中有任何地方可以传递 header 信息。是否有任何其他方法可用于 DELETE 请求 header 信息?

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

您可以实施 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(...)