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
- retrofit缓存
- Retrofit缓存
- Retrofit+okhttp 缓存的
- retrofit+okhttp 实现缓存
- Retrofit集成网络缓存
- 为Retrofit 2.0 添加缓存
- Android Retrofit RxJava实现缓存
- Android网络缓存,retrofit+okhttp
- Cache-Control与retrofit缓存
- 【缓存策略】Retrofit+OkHttp实现缓存处理
- Retrofit缓存数据遇到的问题
- Retrofit缓存设置,处理UnKnownHostException异常信息
- Retrofit—okhttp Cache缓存策略
- Retrofit网络请求+GreenDao数据缓存
- 【Android】Retrofit框架缓存处理(离线缓存等)
- Retrofit+rxjava的缓存设置,以及glide的缓存设置
- Retrofit
- Retrofit
- SMPP协议 20160615
- [C语言]模拟实现C语言库函数atof
- C代码中如何调用C++ C++中如何调用C
- netty即时通信小demo
- Libgdx 之CheckBox ScrollPane
- retrofit缓存
- 实现Runnable接口的类+使用Thread类的实例来创建线程---->通过实现Runnable接口来创建线程类
- css中的距离(参考w3school)
- IDEA项目按ctrl+alt+f10没有反应,run灰色不可用
- 学生管理系统
- word编辑目录页码----去掉前后横线的问题
- UIView动画效果
- 论文解析:人脸检测中级联卷积神经网络的联合训练
- FatFS文件系统介绍及使用例程