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值的缓存对象。
- public 数据内容皆被储存起来,就连有密码保护的网页也储存,安全性很低
- private 数据内容只能被储存到私有的cache,仅对某个用户有效,不能共享
- no-cache 可以缓存,但是只有在跟WEB服务器验证了其有效后,才能返回给客户端
- no-store 请求和响应都禁止被缓存
- max-age: 本响应包含的对象的过期时间
- max-stale: 允许读取过期时间必须小于max-stale 值的缓存对象。
- no-transform 告知代理,不要更改媒体类型,比如jpg,被你改成png.
1、用在request中的cache控制头
- Pragma: no-cache :兼容早起HTTP协议版本 如1.0+
- Cache-Control: no-cache ,表示不希望得到一个缓存内容。只是希望,cache设备可能忽略。
- Cache-Control: no-store,表示client与server之间的设备不能缓存响应内容,并应该删除已有缓存。
- Cache-Control: only-if-cached,表示只接受是被缓存的内容
2、用在response中控制cache的头
- Cache-Control: max-age=3600,用相对于接收到的时间开始可缓存多久
- Cache-Control: s-maxage=3600,与上面类似,只是s-maxage一般用在cache服务器上,并只对public缓存有效
- Expires: Fri, 05 Jul 2002, 05:00:00 GMT基于GMT的时间,绝对时间,但该头容易受到本地错误时间影响
- Cache-Control: must-revalidate 该头表示内容可以被缓存但每次必须询问是否有更新。
以下是几种常见的情况:
- 用户点击“刷新”按钮,就可能有必要跳过缓存,并直接从服务器获取数据(Force a Network Response)。要强制刷新,添加无缓存指令:Cache-Control:no-cache 表示不希望得到一个缓存内容。
- 如果缓存只是用来和服务器做验证,可是设置更有效的
Cache-Control:max-age=0
。设置响应缓存多长时间, 使用Cache-Control: max-age=9600
- 有时你会想显示可以立即显示的资源(Force a Cache Response),使用
Cache-Control: only-if-cached
,表示只接受是被缓存的内容。 - 有时候过期的response比没有response更好,设置最长过期时间来允许过期的response响应:
Cache-Control: max-stale=3600