我已经尝试几乎每个视频,文章和stackoverflow回答,但我 能够缓存回复< / strong>在Retrofit中。
我改造设置是这样的:
private val gson = GsonBuilder()
.setLenient()
.create()!!
private val CACHE_CONTROL = "Cache-Control"
private var cacheSize: Long = 10 * 1024 * 1024 // 10 MB
private var cache = Cache(File(applicationContext.cacheDir, "http-cache"), cacheSize)
private val offlineCacheInterceptor = Interceptor { chain ->
var request = chain.request()
Log.i("datatest", "Internet is availiable : ${isOnline(applicationContext)}")
if (!isOnline(applicationContext)) {
val cacheControl = CacheControl.Builder()
.maxStale(7, TimeUnit.DAYS)
.build()
request = request.newBuilder()
.cacheControl(cacheControl)
.build()
}
chain.proceed(request)
}
private val networkInterceptor = Interceptor { chain ->
val response = chain.proceed(chain.request())
val cacheControl = CacheControl.Builder()
.maxAge(2, TimeUnit.MINUTES)
.build()
response.newBuilder()
.header(CACHE_CONTROL, cacheControl.toString())
.build()
}
private val httpClient = OkHttpClient.Builder()
.addInterceptor(offlineCacheInterceptor)
.addNetworkInterceptor(networkInterceptor)
.cache(cache)
.build()
private val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
但是当我尝试用飞机模式中的手机调用改装API时
我收到以下错误:
无法解析主机&#34; my_url&#34;:没有与主机名关联的地址
我在缓存设置中做错了什么?
我认为我做过一个愚蠢的错误,但我自己并没有看到。