在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
请求?
答案 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(...)