In Spring RestTemplate
we are having the following methods for delete.
@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 DELETE
request with header information?
RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers. setAccept(Collections. singletonList(MediaType. APPLICATION_JSON)); HttpEntity<String> httpEntity = new HttpEntity<>("some body", headers); restTemplate.
I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders . (You can also specify the HTTP method you want to use.) For example, RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.
Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods. The code given below shows how to create Bean for Rest Template to auto wiring the Rest Template object.
RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it's not really that future proof.
You can use the exchange
method (which takes any HTTP request type), rather than using the delete
method:
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);
You can implement ClientHttpRequestInterceptor
and set it for your restTemplate
. In your interceptor:
@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(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With