public final class HttpResponseCache
extends ResponseCache
implements Closeable, OkCacheContainer
java.lang.Object | ||
↳ | java.net.ResponseCache | |
↳ | android.net.http.HttpResponseCache |
将HTTP和HTTPS响应缓存到文件系统,以便它们可以重复使用,节省时间和带宽。 该课程支持HttpURLConnection
和HttpsURLConnection
; 没有平台提供的缓存DefaultHttpClient
或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!
对于某些应用程序,最好在外部存储目录中创建缓存。 外部存储目录上没有访问控制,因此不应将其用于可能包含私有数据的高速缓存。 尽管它通常具有更多的可用空间,但外部存储器是可选的,即使可用,也可以在使用过程中消失。 使用getExternalCacheDir()
检索外部缓存目录。 如果此方法返回null,则您的应用程序应该回退到非缓存或缓存非外部存储。 如果外部存储在使用过程中被移除,则缓存命中率将降至零,并且正在进行的缓存读取将失败。
刷新缓存强制其数据到文件系统。 这可确保写入缓存的所有响应在下次活动开始时都可读。
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.
提高缓存命中率的最佳方法是将Web服务器配置为返回可缓存的响应。 尽管此客户端支持所有HTTP/1.1 (RFC 2068)缓存标头,但它不会缓存部分响应。
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 |
|
---|---|
void |
close() 卸载缓存并释放任何活动资源。 |
void |
delete() 卸载缓存并删除其中的所有内容。 |
void |
flush() 强制缓冲操作到文件系统。 |
CacheResponse |
get(URI uri, String requestMethod, Map<String, List<String>> requestHeaders) 根据请求的URI,请求方法和请求标头检索缓存的响应。 |
int |
getHitCount() 返回由缓存提供响应的HTTP请求的数量。 |
static HttpResponseCache |
getInstalled() 返回当前安装 |
int |
getNetworkCount() 返回要求网络提供响应或验证本地缓存响应的HTTP请求数。 |
int |
getRequestCount() 返回所做的HTTP请求总数。 |
static HttpResponseCache |
install(File directory, long maxSize) 创建一个新的HTTP响应缓存并将其设置为系统默认缓存。 |
long |
maxSize() 返回此缓存用于存储其数据的最大字节数。 |
CacheRequest |
put(URI uri, URLConnection urlConnection) 协议处理程序在获取资源后调用此方法,并且ResponseCache必须决定是否将资源存储在其缓存中。 |
long |
size() 返回当前用于存储此缓存中的值的字节数。 |
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
|
CacheResponse get (URI uri, String requestMethod, Map<String, List<String>> requestHeaders)
根据请求的URI,请求方法和请求标头检索缓存的响应。 通常,在发送请求获取网络资源之前,协议处理程序会调用此方法。 如果返回缓存的响应,则使用该资源。
Parameters | |
---|---|
uri |
URI : a URI used to reference the requested network resource |
requestMethod |
String : a String representing the request method |
requestHeaders |
Map : - a Map from request header field names to lists of field values representing the current request headers |
Returns | |
---|---|
CacheResponse |
a CacheResponse instance if available from cache, or null otherwise |
Throws | |
---|---|
IOException |
int getHitCount ()
返回由缓存提供响应的HTTP请求的数量。 这可能包括通过网络验证的有条件的GET
请求。
Returns | |
---|---|
int |
HttpResponseCache getInstalled ()
返回当前安装 HttpResponseCache
或null如果没有安装高速缓存或它不是一个 HttpResponseCache
。
Returns | |
---|---|
HttpResponseCache |
int getNetworkCount ()
返回要求网络提供响应或验证本地缓存响应的HTTP请求数。
Returns | |
---|---|
int |
int getRequestCount ()
返回所做的HTTP请求总数。 这包括代表客户端处理重定向和重试的客户端请求和请求。
Returns | |
---|---|
int |
HttpResponseCache install (File directory, long maxSize)
创建一个新的HTTP响应缓存并将其设置为系统默认缓存。
Parameters | |
---|---|
directory |
File : the directory to hold cache data. |
maxSize |
long : the maximum size of the cache in bytes. |
Returns | |
---|---|
HttpResponseCache |
the newly-installed cache |
Throws | |
---|---|
IOException |
if directory cannot be used for this cache. Most applications should respond to this exception by logging a warning. |
CacheRequest put (URI uri, URLConnection urlConnection)
协议处理程序在获取资源后调用此方法,并且ResponseCache必须决定是否将资源存储在其缓存中。 如果要缓存资源,put()必须返回一个CacheRequest对象,该对象包含协议处理程序将用于将资源写入缓存的OutputStream。 如果资源不被缓存,则put必须返回null。
Parameters | |
---|---|
uri |
URI : a URI used to reference the requested network resource |
urlConnection |
URLConnection : - a URLConnection instance that is used to fetch the response to be cached |
Returns | |
---|---|
CacheRequest |
a CacheRequest for recording the response to be cached. Null return indicates that the caller does not intend to cache the response. |
Throws | |
---|---|
IOException |
long size ()
返回当前用于存储此缓存中的值的字节数。 如果后台删除处于maxSize()
这可能会大于maxSize()
。 如果无法确定大小,则返回-1
。
Returns | |
---|---|
long |