总是返回代码200 (响应ok),而它应该是304。
以下是我的示例代码。
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)。重复的请求将导致空cacheResponse和响应码200。
我看到了预期的调试日志输出,所以看起来CacheControlInceptor正在正确实例化。我将在响应中获取ETag。响应被正确地缓存在上下文的缓存目录中。我找不出哪里出了问题。
发布于 2020-09-24 09:35:29
除非您完全读取响应,否则OkHttp不会将响应保存到缓存中。它写入缓存作为读取响应体的副作用。
如果您在响应正文完成之前停止读取,OkHttp将不会存储完整的响应,并且缓存条目将不可用。
https://stackoverflow.com/questions/64034913
复制相似问题