1. okhttp框架拥有很好的缓存策略CacheStrategy,并使用DiskLruCache技术对响应的内容进行存储。要建立缓存,要有以下条件:
可以读写的缓存目录
缓存大小的限制
缓存目录应该是私有的,不信任的程序不能读取缓存内容
全局用户唯一的缓存访问实例。okhttp框架全局必须只有一个OkHttpClient实例(new OkHttpClient()),并在第一次创建实例的时候,配置好缓存。
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消息的值,那么客户机可以接收超出超时期指定值之内的响应消息。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。