有一个api有调用限制,在这种情况下,我想缓存响应,如果缓存仍然有效,则不运行网络响应。
首先我有
cache interceptor
fun provideCacheInterceptor(): Interceptor = Interceptor { chain ->
val response = chain.proceed(chain.request())
val cacheControl = CacheControl.Builder()
.maxAge(6, TimeUnit.HOURS)
.maxStale(6, TimeUnit.HOURS)
.onlyIfCached()
.build()
response.newBuilder()
.header("CacheControl", cacheControl.toString())
.build()
}
我将缓存和拦截器附加到客户端
client = OkHttpClient().newBuilder()
.cache(cache)
.addInterceptor(loggingInterceptor)
.addInterceptor(cacheInterceptor)
因此,当我试图检查来自缓存和/或网络的响应时
Log.e("!@#", "cached: ${it.raw().cacheResponse()?.toString()}")
Log.e("!@#", "network: ${it.raw().networkResponse()?.toString()}")
我得到
cached: Response{protocol=http/1.1, code=200, message=, url=https://API}
network: Response{protocol=h2, code=200, message=, url=https://API}
有办法吗
不
在缓存仍然有效时调用网络终结点?