【问题标题】:How to fetch data from network and not from http cache?如何从网络而不是从 http 缓存中获取数据?
【发布时间】:2019-02-28 11:02:04
【问题描述】:

这是我的代码,我添加了 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
}

} }

【问题讨论】:

    标签: android caching retrofit2


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 2017-10-14
      • 1970-01-01
      • 2017-08-20
      • 1970-01-01
      相关资源
      最近更新 更多