Got this error with retrofit2 & OkHttp3. Unable to resolve host “”: No address associated with hostname

前端 未结 4 2063
南笙
南笙 2021-02-12 11:22

I am using the retrofit 2 and OkHttp3 to request data from server. I just added a offline cache code but It\'s not working as expected. I got the error \"Unable to resolve host

4条回答
  •  猫巷女王i
    2021-02-12 11:45

    I had the same error in my project with kotlin, and I fixed it like this:

    client.addInterceptor(provideOfflineCacheInterceptor(context))
    client.addNetworkInterceptor(provideCacheInterceptor(context))
    
    private fun provideOfflineCacheInterceptor(context: Context): Interceptor {
            return Interceptor { chain ->
                var request = chain.request()
                var cacheHeaderValue = if (!hasNetwork(context)!!){
                        "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 1
                    } else {
                        "public, max-age=" + 5
                    }
                request = request.newBuilder().header("Cache-Control", cacheHeaderValue).build()
                chain.proceed(request)
            }
        }
    
        private fun provideCacheInterceptor(context: Context): Interceptor {
            return Interceptor { chain ->
                val request = chain.request()
                var cacheHeaderValue = if (!hasNetwork(context)!!){
                        "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 1
                    } else {
                        "public, max-age=" + 5
                    }
                //request = request.newBuilder().build()
                val response = chain.proceed(request)
                response.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", cacheHeaderValue)
                        .build()
            }
        }
    

提交回复
热议问题