HttpResponseCache Class

Definition

Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and bandwidth.

[Android.Runtime.Register("android/net/http/HttpResponseCache", DoNotGenerateAcw=true)]
public sealed class HttpResponseCache : Java.Net.ResponseCache, IDisposable, Java.Interop.IJavaPeerable, Java.IO.ICloseable
[<Android.Runtime.Register("android/net/http/HttpResponseCache", DoNotGenerateAcw=true)>]
type HttpResponseCache = class
    inherit ResponseCache
    interface ICloseable
    interface IJavaObject
    interface IDisposable
    interface IJavaPeerable
Inheritance
HttpResponseCache
Attributes
Implements

Remarks

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 DefaultHttpClient or AndroidHttpClient. Installation and instances are thread safe.

<h3>Installing an HTTP response cache</h3> Enable caching of all of your application's HTTP requests by installing the cache at application startup. For example, this code installs a 10 MiB cache in the android.content.Context#getCacheDir() application-specific cache directory of the filesystem}:

{@code
              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();
                  }
              }}

This cache will evict entries as necessary to keep its size from exceeding 10 MiB. The best cache size is application specific and depends on the size and frequency of the files being downloaded. Increasing the limit may improve the hit rate, but it may also just waste filesystem space!

For some applications it may be preferable to create the cache in the external storage directory. <strong>There are no access controls on the external storage directory so it should not be used for caches that could contain private data.</strong> Although it often has more free space, external storage is optional and&#8212;even if available&#8212;can disappear during use. Retrieve the external cache directory using android.content.Context#getExternalCacheDir(). 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.

<h3>Cache Optimization</h3> To measure cache effectiveness, this class tracks three statistics: <ul> <li><strong>#getRequestCount() Request Count:</strong> the number of HTTP requests issued since this cache was created. <li><strong>#getNetworkCount() Network Count:</strong> the number of those requests that required network use. <li><strong>#getHitCount() Hit Count:</strong> the number of those requests whose responses were served by the cache. </ul> Sometimes a request will result in a conditional cache hit. If the cache contains a stale copy of the response, the client will issue a conditional GET. The server will then send either the updated response if it has changed, or a short 'not modified' response if the client's copy is still valid. Such responses increment both the network count and hit count.

The best way to improve the cache hit rate is by configuring the web server to return cacheable responses. Although this client honors all HTTP/1.1 (RFC 2068) cache headers, it doesn't cache partial responses.

<h3>Force a Network Response</h3> In some situations, such as after a user clicks a 'refresh' button, it may be necessary to skip the cache, and fetch data directly from the server. To force a full refresh, add the no-cache directive:

{@code
                    connection.addRequestProperty("Cache-Control", "no-cache");
            }

If it is only necessary to force a cached response to be validated by the server, use the more efficient max-age=0 instead:

{@code
                    connection.addRequestProperty("Cache-Control", "max-age=0");
            }

<h3>Force a Cache Response</h3> Sometimes you'll want to show resources if they are available immediately, but not otherwise. This can be used so your application can show something while waiting for the latest data to be downloaded. To restrict a request to locally-cached resources, add the only-if-cached directive:

{@code
                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
                }
            }

This technique works even better in situations where a stale response is better than no response. To permit stale cached responses, use the max-stale directive with the maximum staleness in seconds:

{@code
                    int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
                    connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
            }

<h3>Working With Earlier Releases</h3> This class was added in Android 4.0 (Ice Cream Sandwich). Use reflection to enable the response cache without impacting earlier releases:

{@code
                  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) {
                  }}

Java documentation for android.net.http.HttpResponseCache.

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Properties

Class

Returns the runtime class of this Object.

(Inherited from Object)
Handle

The handle to the underlying Android instance.

(Inherited from Object)
HitCount

Returns the number of HTTP requests whose response was provided by the cache.

Installed

Returns the currently-installed HttpResponseCache, or null if there is no cache installed or it is not a HttpResponseCache.

JniIdentityHashCode (Inherited from Object)
JniPeerMembers
NetworkCount

Returns the number of HTTP requests that required the network to either supply a response or validate a locally cached response.

PeerReference (Inherited from Object)
RequestCount

Returns the total number of HTTP requests that were made.

ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

(Inherited from ResponseCache)
ThresholdType

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

(Inherited from ResponseCache)

Methods

Clone()

Creates and returns a copy of this object.

(Inherited from Object)
Close()

Uninstalls the cache and releases any active resources.

Delete()

Uninstalls the cache and deletes all of its stored contents.

Dispose() (Inherited from Object)
Dispose(Boolean) (Inherited from Object)
Equals(Object)

Indicates whether some other object is "equal to" this one.

(Inherited from Object)
Flush()

Force buffered operations to the filesystem.

Get(URI, String, IDictionary<String,IList<String>>)
GetHashCode()

Returns a hash code value for the object.

(Inherited from Object)
Install(File, Int64)

Creates a new HTTP response cache and sets it as the system default cache.

JavaFinalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object)
MaxSize()

Returns the maximum number of bytes that this cache should use to store its data.

Notify()

Wakes up a single thread that is waiting on this object's monitor.

(Inherited from Object)
NotifyAll()

Wakes up all threads that are waiting on this object's monitor.

(Inherited from Object)
Put(URI, URLConnection)

Allows the protocol handler to cache data after retrieving resources.

SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object)
Size()

Returns the number of bytes currently being used to store the values in this cache.

ToArray<T>() (Inherited from Object)
ToString()

Returns a string representation of the object.

(Inherited from Object)
UnregisterFromRuntime() (Inherited from Object)
Wait()

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>.

(Inherited from Object)
Wait(Int64)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)
Wait(Int64, Int32)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

JavaCast<TResult>(IJavaObject)

Performs an Android runtime-checked type conversion.

JavaCast<TResult>(IJavaObject)
GetJniTypeName(IJavaPeerable)

Applies to