retrofit缓存

来源:互联网 发布:通达oa即时通讯端口 编辑:程序博客网 时间:2024/05/24 13:28

参考文章:

http://www.jianshu.com/p/3a8d910cce38#

http://www.jianshu.com/p/9c3b4ea108a7/comments/1322621


归结下来主要就是下面几步:

1.设置缓存目录

 //设置缓存目录    private void setCacheDirectory(OkHttpClient client){        File httpCacheDirectory = new File(MyApplication.getInstance().getApplicationContext().getExternalCacheDir(), "responses");        client.setCache(new Cache(httpCacheDirectory,10 * 1024 * 1024));    }

2.设置缓存拦截器:

//设置拦截器    private Interceptor setInterceptor(final String path){        Interceptor interceptor = new Interceptor() {            @Override            public Response intercept(Chain chain) throws IOException {                Request request = chain.request();                boolean hasNetWork = Utils.hasNetwork(MyApplication.getInstance().getApplicationContext());                if (!hasNetWork) {                    request = request.newBuilder()                            .cacheControl(CacheControl.FORCE_CACHE)                            .url(path).build();                }                Response response = chain.proceed(request);                if (hasNetWork) {                    int maxAge =60 * 60 * 60; // read from cache for 60 minute                    response.newBuilder()                            .removeHeader("Pragma")                            .header("Cache-Control", "public, max-stale =" + maxAge)                            .build();                } else {                    int maxStale = 60 * 60 * 24 ; // tolerate 1-weeks stale                    response.newBuilder()                            .removeHeader("Pragma")                            .header("Cache-Control", "public ,  max-stale =" + maxStale)                            .build();                }                return response;            }        };        return  interceptor;    }

3.将这些设置到网络请求的client中

OkHttpClient client = new OkHttpClient();client.interceptors().add(setInterceptor(url));setCacheDirectory(client);

或者可以选择其他的两种方式,一种是在服务器API返回就添加缓存headers(cache-control),或者在每一个请求前面加cache-control

@Headers("Cache-Control: public, max-age=3600)@GET("merchants/{shopId}/icon")Observable<ShopIconEntity> getShopIcon(@Path("shopId") long shopId);

另外记一下缓存的其他可能的配置:

1.  noCache  不使用缓存,全部走网络2.  noStore   不使用缓存,也不存储缓存3.  onlyIfCached 只使用缓存4.  maxAge  设置最大失效时间,失效则不使用 需要服务器配合5.  maxStale 设置最大失效时间,失效则不使用 需要服务器配合 感觉这两个类似 还没怎么弄清楚,清楚的同学欢迎留言6.  minFresh 设置有效时间,依旧如上7.  FORCE_NETWORK 只走网络8.  FORCE_CACHE 只走缓存


0 0
原创粉丝点击