See Also: HttpResponseCache Members
Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and bandwidth. This class supports Java.Net.HttpURLConnection and Javax.Net.Ssl.HttpsURLConnection; there is no platform-provided cache for NoType:org/apache/http/impl/client/DefaultHttpClient;Href=../../../../reference/org/apache/http/impl/client/DefaultHttpClient.html or Android.Net.Http.AndroidHttpClient.
java Example
protected void onCreate(Bundle savedInstanceState) { ... try { File httpCacheDir = new File(context.getCacheDir(), "http"); long httpCacheSize = 10 * 1024 * 1024; // 10 MiB HttpResponseCache.install(httpCacheDir, httpCacheSize); catch (IOException e) { Log.i(TAG, "HTTP response cache installation failed:" + e); } } protected void onStop() { ... HttpResponseCache cache = HttpResponseCache.getInstalled(); if (cache != null) { cache.flush(); } }}
For some applications it may be preferable to create the cache in the external storage directory. There are no access controls on the external storage directory so it should not be used for caches that could contain private data. Although it often has more free space, external storage is optional and—even if available—can disappear during use. Retrieve the external cache directory using Android.Content.Context.ExternalCacheDir. If this method returns null, your application should fall back to either not caching or caching on non-external storage. If the external storage is removed during use, the cache hit rate will drop to zero and ongoing cache reads will fail.
Flushing the cache forces its data to the filesystem. This ensures that all responses written to the cache will be readable the next time the activity starts.
The best way to improve the cache hit rate is by configuring the web server to return cacheable responses. Although this client honors all cache headers, it doesn't cache partial responses.
java Example
connection.addRequestProperty("Cache-Control", "no-cache");
java Example
connection.addRequestProperty("Cache-Control", "max-age=0");
java Example
try { connection.addRequestProperty("Cache-Control", "only-if-cached"); InputStream cached = connection.getInputStream(); // the resource was cached! show it catch (FileNotFoundException e) { // the resource was not cached } }
java Example
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
java Example
try { File httpCacheDir = new File(context.getCacheDir(), "http"); long httpCacheSize = 10 * 1024 * 1024; // 10 MiB Class.forName("android.net.http.HttpResponseCache") .getMethod("install", File.class, long.class) .invoke(null, httpCacheDir, httpCacheSize); catch (Exception httpResponseCacheNotAvailable) { }}