3

I have tried through almost every videos, articles and stackoverflow answer but I am not being able to cache the response in Retrofit.

I have retrofit setup is like this :

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()

But when I try to call the retrofit APIs with my phone in Airplane mode

I get the following error :

Unable to resolve host "my_url": No address associated with hostname

What am I doing wrong in the cache setup?

I think there is a stupid mistake I have done but haven't seen by myself.

Jayson Minard
  • 84,842
  • 38
  • 184
  • 227
erluxman
  • 18,155
  • 20
  • 92
  • 126
  • You can have a look at this article: https://medium.com/major-league/need-to-make-your-app-work-offline-without-extra-work-retrofit2-to-the-rescue-22714c358791 I think you should be handling when connected and when disconnected with the Interceptor. – William Da Silva May 22 '18 at 16:09
  • It was due to header problem from server – erluxman May 22 '18 at 16:54

0 Answers0