retrofit2.HttpException:HTTP 504无法满足的请求(仅缓存)Kotlin android

我想将响应缓存2个小时,因此,尝试将缓存添加到我的okhttp客户端中,每次通过网络访问API都可以正常工作,但是下次启用飞机模式时,我们尝试以离线模式获取数据,给出retrofit2.HttpException:HTTP 504无法满足的请求(仅当缓存时) 我已经尝试过在SO上发布的与此异常相关的所有解决方案。请帮助我找出我在做什么错...长期被困在这里。

interface TrendingRepoService {

@GET("/repositories?language=&since=daily")
suspend fun getTrendingRepos() : List<Repo>
}

object RetrofitClient {
  private fun getclient(context: Context): Retrofit {
    val cacheSize = (5 * 1024 * 1024).toLong()    //cache size is 5mb
    val myCache = Cache(File(context.cacheDir,"responses"),cacheSize)
    val okHttpClient = OkHttpClient.Builder()
            .cache(myCache)
            .addInterceptor { chain ->
                var request = chain.request()
                if (hasnetwork(context)!!) {
                    request.newBuilder().removeHeader("Pragma")
                            .addHeader("Cache-Control","public,max-age=" + 5)
                } else {
                    request = request.newBuilder()
                            .removeHeader("Pragma")
                            .addHeader("Cache-Control",only-if-cached,max-stale=" + 60 * 60 * 2)  //cache should expire after 2 hours
                            .build()
                }

                println("network: " + chain.proceed(request).networkResponse())
                println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + myCache.directory().lastModified())
                println("cache: " + chain.proceed(request).cacheResponse())
                chain.proceed(request)
            }
            .build()

    return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl("https://github-trending-api.now.sh")
            .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
            .build()
   }
 fun getTrendingService(context: Context): TrendingRepoService {
    return getclient(context).create(TrendingRepoService::class.java)
}
}

我可以在我的应用程序缓存文件夹中看到以下文件

retrofit2.HttpException:HTTP 504无法满足的请求(仅缓存)Kotlin android

.0.tmp结束文件在高速缓存中存储的文件内容

https://github-trending-api.now.sh/repositories?language=&since=daily 
GET
0
HTTP/1.1 200 
14
date: Mon,04 Nov 2019 19:27:43 GMT
content-type: application/json; charset=utf-8
x-powered-by: Express
access-control-allow-origin: *
etag: W/"4fcb-tcvKxcVttStpWpvGjIHTyk/TMbU"
cache-control: max-age=120
x-now-trace: hel1,bru1,sfo1
x-now-id: hel1:rv96m-1572895662521-476640337170
strict-transport-security: max-age=63072000
x-now-instance: 4008292682
content-encoding: gzip
server: now
OkHttp-Sent-Millis: 1572895661313
OkHttp-Received-Millis: 1572895662894

TLS_AES_256_GCM_SHA384
2
MIIFTzCCBDegAwIBAgISA4Bu+MYBP......
0
TLSv1.3

最大年龄120岁?每当我想通过缓存获取数据时,都会遇到504错误。 当我点击没有网络的API时,缓存文件夹中仅存在日记文件,其他两个文件下次将不存在。

comind 回答:retrofit2.HttpException:HTTP 504无法满足的请求(仅缓存)Kotlin android

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3164050.html

大家都在问