java.lang.Object | ||
↳ | java.net.ResponseCache | |
↳ | android.net.http.HttpResponseCache |
Caches HTTP and HTTPS responses to the filesystem so they may be reused,
saving time and bandwidth. This class supports HttpURLConnection
and HttpsURLConnection
;
there is no platform-provided cache for DefaultHttpClient
or
AndroidHttpClient
.
application-specific
cache directory
of the filesystem}: 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. 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 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.
Request Count:
the number
of HTTP requests issued since this cache was created.
Network Count:
the
number of those requests that required network use.
Hit Count:
the number of
those requests whose responses were served by the cache.
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.
no-cache
directive: 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: connection.addRequestProperty("Cache-Control", "max-age=0");
only-if-cached
directive: 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: int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
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) {
}}
Public Methods | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Uninstalls the cache and releases any active resources.
| |||||||||||
Uninstalls the cache and deletes all of its stored contents.
| |||||||||||
Force buffered operations to the filesystem.
| |||||||||||
Returns the cached response corresponding to the given request.
| |||||||||||
Returns the number of HTTP requests whose response was provided by the
cache.
| |||||||||||
Returns the currently-installed
HttpResponseCache , or null if
there is no cache installed or it is not a HttpResponseCache .
| |||||||||||
Returns the number of HTTP requests that required the network to either
supply a response or validate a locally cached response.
| |||||||||||
Returns the total number of HTTP requests that were made.
| |||||||||||
Creates a new HTTP response cache and sets it as the system default cache.
| |||||||||||
Returns the maximum number of bytes that this cache should use to store
its data.
| |||||||||||
Allows the protocol handler to cache data after retrieving resources.
| |||||||||||
Returns the number of bytes currently being used to store the values in
this cache.
|
[Expand]
Inherited Methods | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
From class
java.net.ResponseCache
| |||||||||||
From class
java.lang.Object
| |||||||||||
From interface
java.io.Closeable
| |||||||||||
From interface
com.android.okhttp.OkCacheContainer
| |||||||||||
From interface
java.lang.AutoCloseable
|
Uninstalls the cache and releases any active resources. Stored contents will remain on the filesystem.
IOException |
---|
Uninstalls the cache and deletes all of its stored contents.
IOException |
---|
Force buffered operations to the filesystem. This ensures that responses written to the cache will be available the next time the cache is opened, even if this process is killed.
Returns the cached response corresponding to the given request.
uri | the request URI. |
---|---|
requestMethod | the request method. |
requestHeaders | a map of request headers. |
CacheResponse
object if the request is available in the cache
or null
otherwise.IOException |
---|
Returns the number of HTTP requests whose response was provided by the
cache. This may include conditional GET
requests that were
validated over the network.
Returns the currently-installed HttpResponseCache
, or null if
there is no cache installed or it is not a HttpResponseCache
.
Returns the number of HTTP requests that required the network to either supply a response or validate a locally cached response.
Returns the total number of HTTP requests that were made. This includes both client requests and requests that were made on the client's behalf to handle a redirects and retries.
Creates a new HTTP response cache and sets it as the system default cache.
directory | the directory to hold cache data. |
---|---|
maxSize | the maximum size of the cache in bytes. |
IOException | if directory cannot be used for this cache.
Most applications should respond to this exception by logging a
warning.
|
---|
Returns the maximum number of bytes that this cache should use to store its data.
Allows the protocol handler to cache data after retrieving resources. The
ResponseCache
decides whether the resource data should be cached
or not. If so, this method returns a CacheRequest
to write the
resource data to. Otherwise, this method returns null
.
uri | the reference to the requested resource. |
---|---|
urlConnection | the connection to fetch the response. |
null
otherwise.IOException |
---|
Returns the number of bytes currently being used to store the values in
this cache. This may be greater than the maxSize()
if a background
deletion is pending. -1
is returned if the size cannot be determined.