Ran Biron
Ran Biron

Reputation: 6365

apache httpclient and etag cache

I'm using Apache HttpClient 4.3.1 and I'm trying to integrate etag validation cache.

I've tried to "drop in" httpclient-cache CachingHttpClientBuilder instead of my usual HttpClientBuilder using instructions in here, but that didn't seem to do any good. While tracing the execution, it seems like a response that has "etag" header (weak etag) isn't considered cache-able - and so isn't retained for the next cycle.

Has anyone managed to use etag validation based cache with Apache HttpClient? I'm also open for alternative implementations.

Notes:

  1. The server returns the first request with a weak etag header (W/"1234"). If the second request to the same URL has "If-None-Match=1234", the server returns 304. This is checked and working.
  2. The server does not send any other cache header (expires, etc).
  3. The whole setup works wonderfully when using a modern browser.

Upvotes: 3

Views: 2034

Answers (1)

Whether a response is considered as cacheable or not is decided in

ResponseCachingPolicy#isResponseCacheable(org.apache.http.HttpRequest, org.apache.http.HttpResponse)

which checks for some headers using

ResponseCachingPolicy#isExplicitlyCacheable

when header 'Expires' is set or the header 'Cache-Control:' has one of the values "max-age" "s-maxage" "must-revalidate" "proxy-revalidate" or "public" the response is considered cacheable.

For us, it worked to add "Cache-Control: 'must-revalidate' to the response on the server, along with the 'Etag' header.

With this settings the apache http client

  • stores the response of the first request in the cache
  • on the second request, sends a request to the server and if this responds with a HttpStatus 304 (Not Modified) returns a HttpStatus 200 (ok) and the original content to the caller

That is how it should be. We are using release 4.5.2 of apache http client cache.

Upvotes: 1

Related Questions