简体   繁体   English

Retrofit2.1.0和okhttp3离线缓存无法正常工作

[英]Retrofit2.1.0 and okhttp3 offline caching not working

I'm trying to implement caching using Retrofit and OkHttp. 我正在尝试使用Retrofit和OkHttp实现缓存。 I am getting '504 Unsatisfiable Request (only-if-cached)' as Error when offline. 离线时我收到'504 Unsatisfiable Request(only-if-cached)'错误。

OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.readTimeout(10, TimeUnit.SECONDS);
        builder.connectTimeout(5, TimeUnit.SECONDS);

        if (isDebug) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
        }

        builder.addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR)
                .addInterceptor(OFFLINE_INTERCEPTOR)
                .cache(provideCache());


        OkHttpClient client = builder.build();




        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(base_url)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        reqinterface = retrofit.create(MyApiInterface.class);

  private static Cache provideCache(){
    Cache cache = null;
    try{

        cache = new Cache(new File(context.getCacheDir(),"baskin-cache"),
                10*1024*1024);
    }catch (Exception e){
        Log.i("zacharia","Could not create Cache");
    }
    return  cache;
}
  private static final Interceptor REWRITE_RESPONSE_INTERCEPTOR = new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        okhttp3.Response originalResponse = chain.proceed(chain.request());
        String cacheControl = originalResponse.header("Cache-Control");

        if (cacheControl == null || cacheControl.contains("no-store") || cacheControl.contains("no-cache") ||
                cacheControl.contains("must-revalidate") || cacheControl.contains("max-age=0")) {
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, max-age=" + 120)
                    .build();
        } else {
            return originalResponse;
        }
    }
};

private static final Interceptor OFFLINE_INTERCEPTOR = new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if (!isOnline()) {
            Log.d("zacharia", "rewriting request");

            int maxStale = 60 * 60 * 24 * 7; // tolerate 4-weeks stale
            request = request.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }

        return chain.proceed(request);
    }
};

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

When online, I am getting 'D/OkHttp: Cache-Control: public, max-age=120' in the log. 在线时,我在日志中得到'D / OkHttp:Cache-Control:public,max-age = 120'。 When offline , 'D/OkHttp: <-- 504 Unsatisfiable Request (only-if-cached)' 离线时,'D / OkHttp:< - 504不满意请求(仅限缓存)'

您可以尝试调试方法okhttp3.internal.cache.CacheInterceptor#intercept(Chain)okhttp3.Cache#get(Request)以查看为什么不返回先前的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM