Got this error with retrofit2 & OkHttp3. Unable to resolve host "<host-name>": No address associated with hostname Got this error with retrofit2 & OkHttp3. Unable to resolve host "<host-name>": No address associated with hostname android android

Got this error with retrofit2 & OkHttp3. Unable to resolve host "<host-name>": No address associated with hostname


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


Your server response has a "Pragma: no-cache" header. You should remove this header in your response interceptor not your request interceptor.

In your current code you've removed it from the request interceptor.

Your provideCacheInterceptor() should look like this:

public static Interceptor provideCacheInterceptor() {    return new Interceptor() {        @Override        public Response intercept(Chain chain) throws IOException {            Response response = chain.proceed(chain.request());            // re-write response header to force use of cache            CacheControl cacheControl = new CacheControl.Builder()                   .maxAge(2, TimeUnit.MINUTES)                   .build();           return response.newBuilder()                    .header(CACHE_CONTROL, cacheControl.toString())                    .removeHeader("Pragma")                    .build();        }    };}


Please check your network "turn ON" in Manifest file permission OFF Airplane mode on Emulator