HTTP FAILED:java.net.UnknownHostException:无法解析主机“www.reddit.com”:没有与主机名关联的地址

时间:2017-01-17 10:17:35

标签: android caching retrofit2 okhttp3

你好我试图缓存我从reddit服务做的GET请求。我用另一个api测试并且工作但我找不到为什么我无法控制缓存的原因。我可以看到缓存数据如何在应用程序设置中上升,当我可以通过互联网连接json时。但是当我关闭互联网连接(飞行模式)时,我收到了这个错误:

  

01-17 06:00:05.524 17363-17429 / com.amirgb.reddittestapp.debug D / OkHttp: - >获得https://www.reddit.com/reddits.json http / 1.1   01-17 06:00:05.524 17363-17429 / com.amirgb.reddittestapp.debug D / OkHttp: - >结束   01-17 06:00:05.531 17363-17429 / com.amirgb.reddittestapp.debug D / OkHttp:< - HTTP FAILED:java.net.UnknownHostException:无法解析主机“www.reddit.com”:没有地址与主机名相关联

我正在测试一个moto g 4 plus api 23我尝试使用https://itunes.apple.com/us/rss/topfreeapplications/limit=20/json服务并且缓存确实有效,所以也许reddit标头有区别?

我的restclient课程:

import android.content.Context;
import android.widget.ImageView;

import com.amirgb.reddittestapp.BuildConfig;
import com.amirgb.reddittestapp.R;
import com.amirgb.reddittestapp.RedditTestApplication;
import com.amirgb.reddittestapp.model.RedditResponse;
import com.amirgb.reddittestapp.util.NetWorkUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public final class RedditApiService {

    private static IRedditApi mRedditApi;
    private static OkHttpClient mClient;

    /**
     * Inits retrofit
     */
    static {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        File httpCacheDirectory = new File(RedditTestApplication.getInstance().getCacheDir(), "reddit");
        Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);

         mClient = new OkHttpClient.Builder()
                .cache(cache)
                .addInterceptor(chain -> {
                    Request request = chain.request();
                    if (NetWorkUtils.isNetworkAvailable(RedditTestApplication.getInstance())) {
                        request = request.newBuilder()
                                .cacheControl(new CacheControl.Builder()
                                        .maxAge(0, TimeUnit.SECONDS)
                                        .maxStale(365, TimeUnit.DAYS).build())
                                .build();
                    }

                    Response originalResponse = chain.proceed(request);
                    if (NetWorkUtils.isNetworkAvailable(RedditTestApplication.getInstance())) {
                        int maxAge = 60 * 60;
                        return originalResponse.newBuilder()
                                .header("Cache-Control", "public, max-age=" + maxAge)
                                .build();
                    } else {
                        int maxStale = 60 * 60 * 24 * 28;
                        return originalResponse.newBuilder()
                                .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                                .build();
                    }
                })
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .build();

        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(IRedditApi.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(mClient)
                .build();
        mRedditApi = mRetrofit.create(IRedditApi.class);
    }

    /**
     * Get subjects from service api
     *
     * @param callback
     */
    public static void getSubjects(Callback<RedditResponse> callback) {
        Call<RedditResponse> call = mRedditApi.getSubjects();
        call.enqueue(callback);
    }

我的网络工具方法:

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();
}

我的改造界面:

public interface IRedditApi {
String BASE_URL = "https://www.reddit.com";

@GET("/reddits.json")
Call<RedditResponse> getSubjects();}

Reddit响应标题:

  

accept-ranges→bytes   access-control-allow-origin→*   access-control-expose-headers→X-Reddit-Tracking,X-Moose   cache-control→max-age = 0,必须重新验证   content-encoding→gzip   content-length→79113   content-type→application / json;字符集= UTF-8   日期→星期二,2017年1月17日09:16:52 GMT   状态→200   strict-transport-security→max-age = 15552000; includeSubDomains;预紧   vary→accept-encoding   通过→1.1清漆   x-cache→MISS   x-cache-hits→0   x-content-type-options→nosniff   x-frame-options→SAMEORIGIN   x-moose→雄伟壮观   x-reddit-tracking→https://pixel.redditmedia.com/pixel/of_destiny.png?v=W9eORuZE%2BzXXBRZc%2BikbQ8aTR0a7BSLeoE9DDYvuCihjMAifTK%2Bdsr%2F0gX8rDES98kR5xK2vVWc%3D   x-served-by→cache-dfw1841-DFW   x-timer→S1484644612.225905,VS0,VE254   x-ua-compatible→IE = edge   x-xss-protection→1;模式=块

1 个答案:

答案 0 :(得分:1)

有一个&#34;必须重新验证&#34;标题,因此您无法直接从缓存中读取

如果您尝试删除它,例如使用charles-proxy,它应该像您期望的那样工作。由于我不知道你想要达到的目的,我无法告诉你最适合你的解决方案。