I am trying to make use of the HttpResponseCache but have had no luck getting it working.
I am installing it like this:
SdCardManager manager = SdCardManager.getSdCardManager(context);
File dir = new File(manager.getAbsolutePathForSdCardFile(""), "http");
Log.e("Test", "Installing cache to " + dir.getAbsolutePath());
HttpResponseCache.install(dir, 10 * 1024 * 1024);
and my connection code is:
try{
URL url = new URL(mUrl);
HttpURLConnection connection = (HttpURLConnection) ((mProxy == null) ? url
.openConnection() : url.openConnection(mProxy.getProxy()));
HttpResponseCache cache = HttpResponseCache.getInstalled();
Log.e("Test", "Req count: " + cache.getRequestCount() + " hit count " + cache.getHitCount() + " size = " + cache.size());
connection.setUseCaches(true);
connection.setDefaultUseCaches(true);
connection.addRequestProperty("Cache-Control", "max-stale=" + (60 * 60 * 24 * 28));
applyHeaders(connection);
connection.setRequestMethod("GET");
connection.setConnectTimeout(mTimeout);
connection.setReadTimeout(mTimeout);
connection.connect();
mStatusCode = connection.getResponseCode();
mStatusMessage = connection.getResponseMessage();
connection.disconnect();
}
catch (IOException ex) {
ex.printStackTrace();
return false;
}
Looking in adb shell, I see the cache directory being created and it has a journal file. However, no more data is ever sent to the directory:
shell@maguro:/storage/emulated/legacy/Android/data/com.snip.pre/files/http $ ls
journal
I flush the cache after each request:
HttpResponseCache cache = HttpResponseCache.getInstalled();
cache.flush();
Any ideas what I am doing wrong? The servers response headers are here:
GET /imgv.oms/0.0.1fd02.a7003c2a HTTP/1.1
Cache-Control: max-stale=2419200
Authorization: Basic bWFydGlubDppc2lz
X-Loginpageredirect: none
Accept: image/*
Accept-Encoding: gzip,deflate
Accept-Language: en-GB
User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.3; Galaxy Nexus Build/JWR66Y)
Host: appsdev2.server.com:81
Connection: Keep-Alive
Cookie: POSESSIONID=F8654323-f7frSyNmAGKsvE4nFXZJQIIy3Io
Is there anything that is preventing it from being cached?
The problem was that I was sending the Authorization header and the standard has specific rules on whether such requests are cacheable or not. See
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html section 14.8
The server was not allowing me to cache the result, as njzk2 alluded too.