400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

2、okhttp响应缓存

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消息的值,那么客户机可以接收超出超时期指定值之内的响应消息。


本文名称:2、okhttp响应缓存
分享URL:http://www.bluegullmedia.com/article/pdoses.html

其他资讯

让你的专属顾问为你服务

0.0472s