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

2022-09-01 22:42:54

在春季,我们有以下删除方法。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


答案 1

您可以使用该方法(采用任何HTTP请求类型),而不是使用该方法:exchangedelete

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

答案 2

您可以为 .在拦截器中:ClientHttpRequestInterceptorrestTemplate

 @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(...)