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.
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:
So if the server starts sending correct cache headers with expiry in the future, it will still work.
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