1. okhttp框架拥有很好的缓存策略CacheStrategy,并使用DiskLruCache技术对响应的内容进行存储。要建立缓存,要有以下条件:
2. okhttp框架获取响应数据有三种方法:
/**
* 返回网络上的数据。如果没有使用网络,则返回null。
*/
public Response networkResponse()
/**
* 返回缓存中的数据。如果不使用缓存,则返回null。对应发送的GET请求,缓存响应和网络响应 * 有可都非空。
*/
public Response cacheResponse()
public Response priorResponse()
3. 代码
OkHttpClient client = new OkHttpClient();
int cacheSize = 10 * 1024 * 1024; // 10 MiB
File cacheDirectory = new File("cache");
if (!cacheDirectory.exists()) {
cacheDirectory.mkdirs();
}
Cache cache = new Cache(cacheDirectory, cacheSize);
client.setCache(cache);
Request request = new Request.Builder()
.header("Cache-Control", "no-cache") // 刷新数据
.url("http://publicobject.com/helloworld.txt")
.build();
Request request = new Request.Builder()
.header("Cache-Control", "max-age=0")
.url("http://publicobject.com/helloworld.txt")
.build();
Request request = new Request.Builder()
.header("Cache-Control", "only-if-cached")
.url("http://publicobject.com/helloworld.txt")
.build();
int maxStale = 60 * 60 * 24 * 28; //4周
Request request = new Request.Builder()
.header("Cache-Control", "max-stale=" + maxStale)
.url("http://publicobject.com/helloworld.txt")
.build();
注:HTTP header中的max-age 和max-stale区别
max-age 指示客户机可以接收生存期不大于指定时间(以秒为单位)的响应。
max-stale 指示客户机可以接收超出超时期间的响应消息。如果指定max-stale消息的值,那么客户机可以接收超出超时期指定值之内的响应消息。