改进504无法满足的请求(仅当缓存时)

时间:2019-05-20 13:12:48

标签: android retrofit2 okhttp3 http-caching

我正在尝试通过Retrofit和OkHttp使用缓存。

我正在将此拦截器添加到OkHttp构建器中。

  @Provides
  @Singleton
  @TokenHttpClient
  internal fun provideTokenOkHttpClient(
          @BaseHttpClient okHttpClient: OkHttpClient,
          cacheInterceptor: NetworkCacheInterceptor): OkHttpClient {
    return okHttpClient.newBuilder()
            .addInterceptor(cacheInterceptor)
            .build()

拦截器如下所示:

class NetworkCacheInterceptor(val context: Context): Interceptor {

  @Throws(IOException::class)
  override fun intercept(chain: Interceptor.Chain): Response {

    var response = chain.request()


    response = if (hasNetwork(context))

      response.newBuilder()
        .removeHeader("Pragma")
        .removeHeader("Cache-Control")
        .header("Cache-Control",
          "public, max-age=${CacheControl.Builder().maxAge(30, TimeUnit.DAYS).build()}")
        .build()
    else {

      response.newBuilder()
        .removeHeader("Pragma")
        .removeHeader("Cache-Control")
        .header("Cache-Control",
          "public, only-if-cached, max-stale=${CacheControl.Builder().maxAge(30, TimeUnit.DAYS).build()}")
        .cacheControl(CacheControl.FORCE_CACHE)
        .build()

      response
    }
    return chain.proceed(response)
  }

}

这种实现方式将响应保存到cache文件夹中。但是离线时它不起作用。我已经厌倦了分离拦截器,并将缓存添加为networkInterceptor,将脱机拦截器添加为普通拦截器,但是它没有用。在这种情况下,不会保存任何缓存。

当我检查缓存的文件时,我看到以下标头:

GET
0
HTTP/1.1 200 
15
Access-Control-Expose-Headers: value
Cache-Control: no-cache
ETag: "01785cb0981d28aa96d58e491dbd6873e"
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: SAMEORIGIN
Referrer-Policy: no-referrer
Content-Type: application/json;charset=UTF-8
Date: Tue, 21 May 2019 07:50:51 GMT
Transfer-Encoding: chunked
Content-Encoding: gzip
OkHttp-Sent-Millis: 1558425050896
OkHttp-Received-Millis: 1558425050928

有什么主意吗?我想念的是什么?

0 个答案:

没有答案