首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试在Android中使用If-None-Match与Etag的问题

尝试在Android中使用If-None-Match与Etag的问题
EN

Stack Overflow用户
提问于 2020-09-24 03:20:25
回答 1查看 148关注 0票数 2

总是返回代码200 (响应ok),而它应该是304。

以下是我的示例代码。

代码语言:javascript
复制
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:

代码语言:javascript
复制
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类:

代码语言:javascript
复制
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()
    }
}

下面是我提出请求的方式:

代码语言:javascript
复制
val response: Response<ResponseBody?> = downloadService.downloadResourceIfNoneMatch(downloadUrl, "2377a02e14b7df5100ee9ffebbb8443a")

我正在使用硬编码的ETag进行测试。当请求发出两次时,它不会显示预期的行为(即响应代码304)。重复的请求将导致空cacheResponse和响应码200。

我看到了预期的调试日志输出,所以看起来CacheControlInceptor正在正确实例化。我将在响应中获取ETag。响应被正确地缓存在上下文的缓存目录中。我找不出哪里出了问题。

EN

回答 1

Stack Overflow用户

发布于 2020-09-24 09:35:29

除非您完全读取响应,否则OkHttp不会将响应保存到缓存中。它写入缓存作为读取响应体的副作用。

如果您在响应正文完成之前停止读取,OkHttp将不会存储完整的响应,并且缓存条目将不可用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64034913

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档