DevSupportAndroid备忘录鱼乐

OkHttp3 Cache

2016-11-11  本文已影响2080人  wIsper

OkHttp3的缓存Cache与之前版本有API上面的变化。先看官方文档的说明:

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:

Request request = new Request.Builder()
    .cacheControl(new CacheControl.Builder().noCache().build())
    .url("http://publicobject.com/helloworld.txt")
    .build();

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

Request request = new Request.Builder()
    .cacheControl(new CacheControl.Builder()
       .maxAge(0, TimeUnit.SECONDS)
       .build())
    .url("http://publicobject.com/helloworld.txt")
    .build();

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:

 Request request = new Request.Builder()
     .cacheControl(new CacheControl.Builder()
         .onlyIfCached()
         .build())
     .url("http://publicobject.com/helloworld.txt")
     .build();
 Response forceCacheResponse = client.newCall(request).execute();
 if (forceCacheResponse.code() != 504) {
   // The resource was cached! Show it.
 } else {
   // 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:

Request request = new Request.Builder()
    .cacheControl(new CacheControl.Builder()
        .maxStale(365, TimeUnit.DAYS)
        .build())
    .url("http://publicobject.com/helloworld.txt")
    .build();

The CacheControl class can configure request caching directives and parse response caching directives. It even offers convenient constants CacheControl.FORCE_NETWORK and CacheControl.FORCE_CACHE that address the use cases above.


正如官方文档所讲,我们要使用OkHttp的Cache,首先需要指定缓存的路径和大小

OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .cache(new Cache(context.getCacheDir(), 10 * 1024 * 1024))
    .build();

缓存路径下会看到xxx.0和xxx.1文件,分别缓存的是Request和Response

然后在构建Request的时候,可以加入CacheControl,比如设置最大缓存时间为5分钟

public Request buildRequest() {
    CacheControl cacheControl = new CacheControl.Builder()
        .maxAge(60 * 5, TimeUnit.SECONDS).build();
    return new Request.Builder().cacheControl(cacheControl).build();
}

OkHttp还提供了拦截器机制Interceptor

简单实现

public class NetInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        // 如果没有网络,则启用 FORCE_CACHE
        /*if (!NetworkUtils.isNetworkConnected())
        {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        }*/

        Response response = chain.proceed(request);

        /** 设置max-age为5分钟之后,这5分钟之内不管有没有网, 都读缓存。
         * max-stale设置为5天,意思是,网络未连接的情况下设置缓存时间为1天 */
        CacheControl cacheControl = new CacheControl.Builder()
                .maxAge(5, TimeUnit.MINUTES)
                .maxStale(5, TimeUnit.DAYS)
                .build();

        return response.newBuilder()
                //在这里生成新的响应并修改它的响应头
                .header("Cache-Control", cacheControl.toString())
                .removeHeader("Pragma").build();
    }
}

然后再构建OkHttpClient的时候加入addNetworkInterceptor

OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addNetworkInterceptor(new NetInterceptor());
    .cache(new Cache(context.getCacheDir(), 10 * 1024 * 1024))
    .build();

从业务上来说,当没有网络的时候,缓存永远不失效;当有网络的时候如果如果请求失败则会返回缓存,如果请求成功,在会根据缓存设置的有效期,来决定是否访问缓存;同时可以调用刷新缓存,但是刷新缓存之后,新获取的数据依然会使用默认的缓存有效期。以下为通过Interceptor实现的缓存机制:

LocalCacheInterceptor来实现本地缓存的获取策略

/**
 * 此拦截器为拦截本地缓存,不会对缓存数据造成影响,只会影响到是否能获取到本地缓存数据
 */
public class LocalCacheInterceptor implements Interceptor {

    private int maxCacheSeconds;
    private Headers commonHeaders;

    public LocalCacheInterceptor(int maxCacheSeconds, Headers commonHeaders) {
        this.maxCacheSeconds = maxCacheSeconds;
        this.commonHeaders = commonHeaders;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        CacheControl cacheControl = new CacheControl.Builder().maxAge(maxCacheSeconds, TimeUnit.SECONDS)
                .maxStale(0, TimeUnit.SECONDS).build();
        Request request = chain.request();
        Request.Builder builder = request.newBuilder().cacheControl(cacheControl);
        if (commonHeaders != null) {
            for (String name : commonHeaders.names()) {
                builder.addHeader(name, commonHeaders.get(name));
            }
        }
        request = builder.build();
        if (AppUtils.isNetworkAvailable()) {
            try {
                Response response = chain.proceed(request);
                if (response.isSuccessful()) {
                    return response;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //if request failed. always load in cache
        cacheControl = new CacheControl.Builder().maxAge(Integer.MAX_VALUE, TimeUnit.SECONDS).maxStale(Integer.MAX_VALUE, TimeUnit.SECONDS).build();
        request = builder.cacheControl(cacheControl).build();
        return chain.proceed(request);
    }
}

NetCacheInterceptor主要来实现Response的重写,来确保返回最新的数据设置缓存有效期

/**
 * 此拦截器为网络缓存器。只会改变本地缓存时间的大小,不会影响到是否能获取到本地缓存文件
 */
public class NetCacheInterceptor implements Interceptor {
    private int maxCacheSeconds;
    private Headers commonHeaders;

    public NetCacheInterceptor(int maxCacheSeconds, Headers commonHeaders) {
        this.maxCacheSeconds = maxCacheSeconds;
        this.commonHeaders = commonHeaders;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        if (commonHeaders != null) {
            for (String name : commonHeaders.names()) {
                builder.addHeader(name, commonHeaders.get(name));
            }
        }
        request = builder.build();
        Response originalResponse = chain.proceed(request);
        // rewrite the response headers to support cache.
        if (AppUtils.isNetworkAvailable()) {
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, max-age=" + EPocketHttpService.DEFAULT_CACHE_MAX_SECONDS)
                    .build();
        } else {
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + Integer.MAX_VALUE)
                    .build();
        }
    }
}

构建OkhttpClient

OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addInterceptor(new LocalCacheInterceptor(maxCacheSeconds, commonHeaders))
    .addNetworkInterceptor(new NetCacheInterceptor(maxCacheSeconds, commonHeaders))
    .cache(new Cache(context.getCacheDir(), 10 * 1024 * 1024)).build();

需要说明的是:OkHttp的Cache是根据URL以及请求参数来生成的,并且不支持POST请求。

至于为什么不支持Post请求,官方也没有给出详细说明。我个人的猜测是普遍来讲,Get请求是获取数据的(比如刷feed);Post请求是提交数据的(比如提交表单)。从这个角度上讲,对于Get请求做缓存是合适的,而Post要不要做有待商榷。但是有些公司喜欢全部都用Post请求,一方面是为了突破get请求最大长度的限制,还有一个方面的考虑是不想把参数之间暴露给用户,这种情况下想做Http缓存还得想想别的办法。其实从标准化来讲,更倾向的是OkHttp的这种设计,只是作为一个完善的网络库而言,不支持Post的缓存也是让人诟病。


补充一下Cache-Control的说明:

服务器在返回响应时,还会发出一组 HTTP 头,用来描述内容类型、长度、缓存指令、验证令牌等。例如,在上图的交互中,服务器返回了一个 1024 字节的响应,指导客户端缓存响应长达 120 秒,允许读取过期时间小于86400值的缓存对象。

1、用在request中的cache控制头

2、用在response中控制cache的头

以下是几种常见的情况:

上一篇 下一篇

猜你喜欢

热点阅读