用Retrofit2& OkHttp3.无法解析主机“<主机名>":没有与主机名关联的地址 [英] Got this error with retrofit2 & OkHttp3. Unable to resolve host "<host-name>": No address associated with hostname

查看:661
本文介绍了用Retrofit2& OkHttp3.无法解析主机“<主机名>":没有与主机名关联的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用改造2和OkHttp3从服务器请求数据.我刚刚添加了一个离线缓存代码,但是它没有按预期工作.我收到错误无法解析主机<>":没有与主机名关联的地址".

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

推荐答案

我在使用kotlin的项目中遇到了相同的错误,并按以下步骤修复了它:

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

这篇关于用Retrofit2&amp; OkHttp3.无法解析主机“&lt;主机名&gt;":没有与主机名关联的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆