Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android volley - Override Cache Timeout for JSON request

I'm trying to cache JSON requests from a server, however, they are incorrectly using the Cache-Control header, amongst others (everything expires in the past). I want to override it so that calls are cached for say, 3 hours, regardless of what the server requests. Is that possible? The documentation for Volley is Scarce.

like image 530
StackOverflowed Avatar asked Dec 16 '22 08:12

StackOverflowed


1 Answers

You might subclass the JsonObjectRequest class and overwrite parseNetworkResponse. You will notice the call to HttpHeaderParser.parseCacheHeaders - it's a good place to start :] just wrap this call or replace it and provide your own dummy Cache header configuration object [with your proprietary clientside cache time] to Response.success.

In my implementation it looks like this:

parseNetworkResponse

return Response.success(payload, enforceClientCaching(HttpHeaderParser.parseCacheHeaders(response), response));

with enforceClientCaching related members being

protected static final int defaultClientCacheExpiry = 1000 * 60 * 60; // milliseconds; = 1 hour

protected Cache.Entry enforceClientCaching(Cache.Entry entry, NetworkResponse response) {
    if (getClientCacheExpiry() == null) return entry;

    long now = System.currentTimeMillis();

    if (entry == null) {
        entry = new Cache.Entry();
        entry.data = response.data;
        entry.etag = response.headers.get("ETag");
        entry.softTtl = now + getClientCacheExpiry();
        entry.ttl = entry.softTtl;
        entry.serverDate = now;
        entry.responseHeaders = response.headers;
    } else if (entry.isExpired()) {
        entry.softTtl = now + getClientCacheExpiry();
        entry.ttl = entry.softTtl;
    }

    return entry;
}

protected Integer getClientCacheExpiry() {
    return defaultClientCacheExpiry;
}

It handles 2 cases:

  • no Cache headers were set
  • Server cache entry indicates expired item

So if the server starts sending correct cache headers with expiry in the future, it will still work.

like image 87
Makibo Avatar answered Jan 10 '23 04:01

Makibo