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

5

21

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 "<>": No address associated with hostname."

This occurs when It's try to get the retrieve data from the cache(when no internet connection). A code snippet is below.

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())
                    .build();
        }
    };
}

public static Interceptor provideOfflineCacheInterceptor() {
    return new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            if (!hasNetwork) {
                CacheControl cacheControl = new CacheControl.Builder()
                        .onlyIfCached()
                        .maxStale(7, TimeUnit.DAYS)
                        .build();

                request = request.newBuilder()
                        .removeHeader("Pragma")
                        .cacheControl(cacheControl)
                        .build();
            }

            return chain.proceed(request);
        }
    };
}

private static Cache provideCache() {
    Cache cache = null;
    try {
        cache = new Cache(new File(AdeptAndroid.getInstance().getCacheDir(), "http-cache"),
                10 * 1024 * 1024); // 10 MB
    } catch (Exception e) {
        Log.d("Test", "Could not create Cache!");
    }
    return cache;
}

And finally a method which combine all of these is here.

private static OkHttpClient provideOkHttpClient() {
    return new OkHttpClient.Builder()
            .addInterceptor(provideHttpLoggingInterceptor())
            .addInterceptor(provideOfflineCacheInterceptor())
            .addNetworkInterceptor(provideCacheInterceptor())
            .cache(provideCache())
            .build();
}
Tymon answered 30/6, 2016 at 5:34 Comment(9)
Setting header this way (exactly 50000) solved the issue. .header("Cache-Control", String.format("max-age=%d", 50000))Elnoraelnore
@WaqarYounis Thanks for the reply but it's not working either.Tymon
Did you solve this issue? I have this issue when waking up the app from background using GCM.Milter
@Tymon did you find any workaround, cause having the same issue and not able to get through it.Vixen
@dexmorgan Nah! sorry to say this but till now not found any solution for this.Tymon
@Tymon have you find the solution yet, I have the same problemCloison
@KrunalKapadiya Sorry, not yetTymon
What have you done in this case?Cloison
Have you found any solution ?Horribly
G
3

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()
        }
    }
Granth answered 28/12, 2018 at 14:22 Comment(0)
D
1

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();
        }
    };
}
Decapitate answered 22/12, 2017 at 16:57 Comment(1)
Not solving my problem: #52876779Gandhi
R
-1

For me the error was thrown because there was no internet connection in emulator.

Retiform answered 4/5, 2021 at 13:22 Comment(0)
U
-2

This happens when trying to access a hostname that is not available on the connected network. Check whether or not you can access this URL through the web browser of the device. If not: There is your problem.

Upton answered 22/11, 2019 at 11:33 Comment(0)
G
-3

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

Gravitative answered 7/1, 2019 at 4:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.