如何从网络而不是从HTTP缓存中获取数据?

时间:2018-09-24 21:37:00

标签: android caching retrofit2

这是我的代码,我添加了CacheHeaderInterceptor,但是其中一个请求 在某些情况下,需要从网络强制调用而不是检索缓存响应 但是由于我添加了CacheHeaderInterceptor,所以它在第一次调用后从未调用过。 但我需要检查并基于从网络中获取的检查或检索缓存响应

@Singleton
@Provides
fun httpClient(context: Context, @Named(“UserPreferences”) preferences: SharedPreferences): OkHttpClient {
val appCacheDir = context.cacheDir
val httpCacheDir = File(appCacheDir, HTTP_CACHE_DIRNAME)
if (!httpCacheDir.exists()) {
  httpCacheDir.mkdirs()
}
val builder = OkHttpClient.Builder()
val authInterceptor = LegacyAuthInterceptor(preferences, userAuthRelay)
builder.addNetworkInterceptor(authInterceptor)

if (BuildConfig.DEBUG) {
  builder.addNetworkInterceptor(StethoInterceptor())
}

builder.addNetworkInterceptor(CacheHeaderInterceptor(isStoreUpdatedRelay))

return builder
    .cache(Cache(httpCacheDir, MAX_HTTP_CACHE_SIZE))
    .connectTimeout(30, SECONDS)
    .writeTimeout(30, SECONDS)
    .readTimeout(30, SECONDS)
    .retryOnConnectionFailure(true)
    .build()
  }

  class CacheHeaderInterceptor(private val isUpdatedRelay: BehaviorRelay<Boolean>) : Interceptor {



override fun intercept(chain: Interceptor.Chain): Response {

chain.request().headers().get(CustomCacheHeader.CUSTOM_CACHE_HEADER_KEY)
    ?: return chain.proceed(chain.request()) 



val maxAge = chain.request().headers().values(CustomCacheHeader.CUSTOM_CACHE_HEADER_KEY).firstOrNull()?.toLongOrNull()

val modifiedRequest = chain.request().newBuilder().removeHeader(CustomCacheHeader.CUSTOM_CACHE_HEADER_KEY).build()

val originalResponse = chain.proceed(modifiedRequest)
return when {
  isUpdatedRelay.value -> {
    val modifiedResponse = originalResponse.newBuilder()
        .addHeader("Cache-Control", "no-cache")
        .build()
    isStoreUpdatedRelay.accept(false)
    modifiedResponse
  }
  maxAge != null -> {
    // Add Cache-Control to the response.
    val modifiedResponse = originalResponse.newBuilder()
        .removeHeader("Cache-Control")
        .removeHeader("Pragma")
        .addHeader("Cache-Control", "max-age=$maxAge")
        .build()
    modifiedResponse
  }
  else -> // Missing max-age, proceed with original response.
    originalResponse
}

} }

1 个答案:

答案 0 :(得分:0)

我找到了问题的解决方案 添加addInterceptor() 有addNetworkInterceptor()和addInterceptor()。