参考文章:
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 只走缓存