【发布时间】:2021-01-10 01:34:24
【问题描述】:
当它应该是 304 时总是返回代码 200(响应正常)。
这是我的示例代码。
import okhttp3.ResponseBody
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Streaming
import retrofit2.http.Url
interface DownloadService {
@Streaming
@GET
suspend fun downloadResourceIfNoneMatch(
@Url url: String,
@Header("If-None-Match") vararg eTags: String
): Response<ResponseBody?>
}
这是我正在使用的 OkHttpClient:
val cacheSize: Long = 10 * 1024 * 1024 // 100 MB
val cache = Cache(context.cacheDir, cacheSize)
val cacheControlInterceptor = CacheControlInterceptor(context)
return OkHttpClient.Builder()
.cache(cache)
.addInterceptor(cacheControlInterceptor)
.addNetworkInterceptor(cacheControlInterceptor)
.addNetworkInterceptor(loggingInterceptor)
.build()
这是我的 CacheControlInterceptor 类:
import android.content.Context
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import timber.log.Timber
import java.io.IOException
class CacheControlInterceptor constructor(val context: Context) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
Timber.d("cache control interceptor")
var request: Request = chain.request()
if (request.method == "GET") {
request = request.newBuilder()
.build()
}
val originalResponse: Response = chain.proceed(request)
return originalResponse.newBuilder()
.header("Cache-Control", "private, must-revalidate")
.build()
}
}
这是我提出请求的方式:
val response: Response<ResponseBody?> = downloadService.downloadResourceIfNoneMatch(downloadUrl, "2377a02e14b7df5100ee9ffebbb8443a")
我正在使用硬编码的 ETag 进行测试。当请求发出两次时,它不会显示预期的行为(即响应代码 304)。重复请求导致空缓存响应和响应代码 200。
我看到了预期的调试日志输出,所以看起来 CacheControlInceptor 正在正确实例化。我在回复中收到了 ETag。响应在上下文的缓存目录中正确缓存。我不知道出了什么问题。
【问题讨论】:
标签: android caching retrofit2 okhttp etag