Question

In my Application onCreate, I'm creating a 10MB cache:

try
{
    File httpCacheDir = new File(getApplicationContext().getCacheDir(), Constants.AppName);
    long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
    HttpResponseCache.install(httpCacheDir, httpCacheSize);
}
catch (IOException ex)
{
    Log.i(Constants.AppName, "HTTP response cache installation failed: " + ex);
}

And my call to a resource:

OkHttpClient client = new OkHttpClient();
client.setResponseCache(HttpResponseCache.getInstalled());

HttpURLConnection connection = client.open(url);
connection.addRequestProperty("Cache-Control", "max-age=60");
InputStream inputStream = connection.getInputStream();

I'll initialize this call twice, within 10 seconds of one another, and the OkHttp-Response-Source header is always NETWORK 200.

for (Map.Entry<String, List<String>> k : connection.getHeaderFields().entrySet())
{
    for (String v : k.getValue())
    {
        Log.d(Constants.AppName, k.getKey() + ": " + v);
    }
}

What am I missing here?

Was it helpful?

Solution

OkHttp implement the HTTP 1.1 RFC for HTTP cache. That means, for any URL your are trying to reach, the response needs to return at least the Cache-Control header:

The basic cache mechanisms in HTTP/1.1 (server-specified expiration times and validators) are implicit directives to caches. In some cases, a server or client might need to provide explicit directives to the HTTP caches. We use the Cache-Control header for this purpose.

The Cache-Control header allows a client or server to transmit a variety of directives in either requests or responses. These directives typically override the default caching algorithms. As a general rule, if there is any apparent conflict between header values, the most restrictive interpretation is applied (that is, the one that is most likely to preserve semantic transparency). However,

in some cases, cache-control directives are explicitly specified as weakening the approximation of semantic transparency (for example, "max-stale" or "public").

The cache-control directives are described in detail in section 14.9.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top