retrofit缓存

参考文章:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值