我想缓存 200 个请求,并在没有互联网/遇到一些 api 错误时从缓存中检索数据,但无法从缓存中获取任何数据:
我的网络拦截器
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val originalResponse = chain.proceed(request)
// Only cache responses with status code 200
if (originalResponse.code == 200) {
val cacheResponse = originalResponse.newBuilder()
.header(
name = HeadersFields.CACHE_CONTROL,
value = HeadersFields.getPublicMaxAgeHeader(cacheTimeInSecond = 3600
)
)
.removeHeader(name = HeadersFields.PRAGMA)
.build()
return cacheResponse
}
return originalResponse
}
应用程序拦截器
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val cacheRequest =
request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).removeHeader(name = HeadersFields.PRAGMA).build()
return try {
chain.proceed(request)
} catch (e: Exception) {
when (e) {
is ServerError, is SocketTimeoutException, is TimeoutException, is ConnectException -> {
chain.proceed(cacheRequest)
}
else -> chain.proceed(request)
}
}
}
我将 okhttp 客户端实例注入两个拦截器以监视缓存,并且我看到记录(在下一个请求后增加)
但是我得到了
(httpStatusCode=504,httpMessage=无法满足的请求(仅在缓存时),responseBody=) 块引用
我的客户端(我只有一个 OkHttpClient 可以到处注入)。我将 maxRequestsPerHost 设置为 1 以避免竞争条件,但这没有帮助:/
private const val CONNECT_TIMEOUT_SEC = 60L
private const val CACHE_MAX_SIZE = 50L * 1024L * 1024L
fun getOkHttpClient(context: Context): OkHttpClient {
val appCache = Cache(directory = context.cacheDir, maxSize = CACHE_MAX_SIZE)
val client = OkHttpClient.Builder().apply {
cache(appCache)
connectTimeout(timeout = CONNECT_TIMEOUT_SEC, unit = TimeUnit.SECONDS)
}.build()
client.dispatcher.maxRequestsPerHost = 1
return client
}
您可能想在 OkHttp 的内部 CacheStrategy 类中放置一个断点,该类决定缓存的响应是否满足请求。