Renat Gatin
Renat Gatin

Reputation: 6394

How to stop org.springframework.web.client.RestTemplate caching the response?

In my Spring-boot project for REST HTTP calls I am using org.springframework.web.client.RestTemplate.

The problem is that it is caching the response, meaning that when I call it for the first time I get back the right response, but when I update data on server related to current API and when I call same API for the second time it still returns me the old response, so it is probably taking the ResponseEntity<T> from cache? I am not sure.. How to get the latest version of the response each time I call same API?

Here is how I make HTTP call

public <T> ResponseEntity<T> doQueryApi(String url, HttpMethod httpMethod, Object anyObject, HttpHeaders requestHeaders, Class<T> responseType) throws RestClientException {

        HttpEntity requestEntity = new HttpEntity(anyObject, requestHeaders);
        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, requestEntity, responseType);
        return responseEntity;
    }
}

Upvotes: 9

Views: 10663

Answers (1)

Jorge
Jorge

Reputation: 1176

You can try force no-caching requests in request headers this way:

// Force the request expires
requestHeaders.setExpires(0);
// Cache-Control: private, no-store, max-age=0
requestHeaders.setCacheControl("private, no-store, max-age=0");

I had similiar problem and it worked fine.

Upvotes: 4

Related Questions