Most visited

Recently visited

Added in API level 13

HttpResponseCache

public final class HttpResponseCache
extends ResponseCache implements Closeable, OkCacheContainer

java.lang.Object
   ↳ java.net.ResponseCache
     ↳ android.net.http.HttpResponseCache


将HTTP和HTTPS响应缓存到文件系统,以便它们可以重复使用,节省时间和带宽。 该课程支持HttpURLConnectionHttpsURLConnection ; 没有平台提供的缓存DefaultHttpClientAndroidHttpClient 安装和实例是线程安全的。

Installing an HTTP response cache

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 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,则您的应用程序应该回退到非缓存或缓存非外部存储。 如果外部存储在使用过程中被移除,则缓存命中率将降至零,并且正在进行的缓存读取将失败。

刷新缓存强制其数据到文件系统。 这可确保写入缓存的所有响应在下次活动开始时都可读。

Cache Optimization

To measure cache effectiveness, this class tracks three statistics: 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.

提高缓存命中率的最佳方法是将Web服务器配置为返回可缓存的响应。 尽管此客户端支持所有HTTP/1.1 (RFC 2068)缓存标头,但它不会缓存部分响应。

Force a Network Response

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:
   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");
 

Force a Cache Response

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:
   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);
 

Working With Earlier Releases

This class was added in Android 4.0 (Ice Cream Sandwich). Use reflection to enable the response cache without impacting earlier releases:
   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) {
       }

Summary

Public methods

void close()

卸载缓存并释放任何活动资源。

void delete()

卸载缓存并删除其中的所有内容。

void flush()

强制缓冲操作到文件系统。

CacheResponse get(URI uri, String requestMethod, Map<StringList<String>> requestHeaders)

根据请求的URI,请求方法和请求标头检索缓存的响应。

int getHitCount()

返回由缓存提供响应的HTTP请求的数量。

static HttpResponseCache getInstalled()

返回当前安装 HttpResponseCache或null如果没有安装高速缓存或它不是一个 HttpResponseCache

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

Public methods

close

Added in API level 13
void close ()

卸载缓存并释放任何活动资源。 存储的内容将保留在文件系统上。

Throws
IOException

delete

Added in API level 13
void delete ()

卸载缓存并删除其中的所有内容。

Throws
IOException

flush

Added in API level 13
void flush ()

强制缓冲操作到文件系统。 这可确保写入缓存的响应在下次打开缓存时可用,即使此过程被终止。

get

Added in API level 13
CacheResponse get (URI uri, 
                String requestMethod, 
                Map<StringList<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

getHitCount

Added in API level 13
int getHitCount ()

返回由缓存提供响应的HTTP请求的数量。 这可能包括通过网络验证的有条件的GET请求。

Returns
int

getInstalled

Added in API level 13
HttpResponseCache getInstalled ()

返回当前安装 HttpResponseCache或null如果没有安装高速缓存或它不是一个 HttpResponseCache

Returns
HttpResponseCache

getNetworkCount

Added in API level 13
int getNetworkCount ()

返回要求网络提供响应或验证本地缓存响应的HTTP请求数。

Returns
int

getRequestCount

Added in API level 13
int getRequestCount ()

返回所做的HTTP请求总数。 这包括代表客户端处理重定向和重试的客户端请求和请求。

Returns
int

install

Added in API level 13
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.

maxSize

Added in API level 13
long maxSize ()

返回此缓存用于存储其数据的最大字节数。

Returns
long

put

Added in API level 13
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

size

Added in API level 13
long size ()

返回当前用于存储此缓存中的值的字节数。 如果后台删除处于maxSize()这可能会大于maxSize() 如果无法确定大小,则返回-1

Returns
long

Hooray!