我想知道如何缓存来自Web服务器(返回json数据)的okHTTP响应?
我希望我的应用程序下载RecycleView所需的所有数据,并在用户第一次运行应用程序时将其缓存 - 并避免重新下载并从Web服务器解析所有相同的数据(如果数据未更改)。
我尝试获取响应标头,但这就是我得到的结果:
Request URL: https://somedomain.com/wp-json/?categories=3&per_page=100&status=publish
Request Method: GET
Status Code: 200 OK
Remote Address: 176.28.12.139:443
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages
Allow: GET
Connection: keep-alive
Content-Encoding: gzip
Content-Type: application/json; charset=UTF-8
Date: Fri, 23 Mar 2018 15:41:23 GMT
Link: <https://somedomain.com/wp-json/>; rel="https://api.w.org/"
Server: nginx
Transfer-Encoding: chunked
Vary: Accept-Encoding
X-Content-Type-Options: nosniff
X-Powered-By: PleskLin
X-Powered-By: PHP/7.1.15
X-Robots-Tag: noindex
X-WP-Total: 43
X-WP-TotalPages: 1
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: hr,en-US;q=0.9,en;q=0.8,de;q=0.7,nb;q=0.6
Connection: keep-alive
Host: somedomain.com
Referer: https://somedomain.com/somedir/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
categories: 3
per_page: 100
status: publish
我已经读过,我可以从服务器响应中找到 ETAG或Last-Modified 以检查是否有任何更改,但正如您所看到的,没有这样的事情。
如果应用程序只需要在第一次运行时下载数据,那么您是否知道该怎么做?之后只有在数据发生变化时才会这样做?
答案 0 :(得分:1)
你需要像这样的缓存拦截器:
public class CacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(15, TimeUnit.MINUTES) // 15 minutes cache
.build();
return response.newBuilder()
.removeHeader("Pragma")
.removeHeader("Cache-Control")
.header("Cache-Control", cacheControl.toString())
.build();
}
}
将此Cache
的拦截器添加到您的OkHttpClient
,如下所示:
File httpCacheDirectory = new File(applicationContext.getCacheDir(), "http-cache");
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(httpCacheDirectory, cacheSize);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new CacheInterceptor())
.cache(cache)
.build();
答案 1 :(得分:0)
只需向OkHttp客户端添加缓存即可。 首先,您需要创建缓存:
int cacheSize = 10 * 1024 * 1024;
Cache cache = new Cache(cacheDirectory, cacheSize);
请注意,使用此代码,您可以提供大小限制为10MB的缓存。在此之后,您将使用以下代码创建客户端:
OkHttpClient client = new OkHttpClient.Builder()
.cache(cache)
.build();
客户端将尊重缓存相关的标头。您可以参考官方文档以获取更多详细信息: https://github.com/square/okhttp/wiki/Recipes