改型缓存问题

时间:2019-04-13 16:30:51

标签: java android caching retrofit2

我在使用Retrofit进行缓存时遇到了一些麻烦。看来当我离线时,它甚至不查看缓存。这是示例:


这就是我进行CacheReady改装的方式

public class RetrofitCached {
    private static final String BASE_URL = "http://www.omdbapi.com";
    private static final String TAG=RetrofitCached.class.getSimpleName();

    public static boolean isNetworkAvailable(Context context) {

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

    public static Retrofit getCacheEnabledRetrofit(final Context context) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cache(new Cache(context.getCacheDir(), 5 * 1024 * 1024))
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                          Response originalResponse = chain.proceed(chain.request());
                          Log.d(TAG,"ORIGINAL RESPPONSE HEADERS "+originalResponse.headers().toMultimap());


                        Log.d(TAG,"Request is here");
                        if(isNetworkAvailable(context)) {
                            Log.d(TAG,"WE HAVE INTERNET");
                            Log.d(TAG,"If less then 1 minute, should read from cache");
                            int maxAge = 60;
                            return originalResponse.newBuilder()
                                    .header("Cache-Control", "public, max-age=" + maxAge)
                                    .build();
                        }
                        else {
                            Log.d(TAG,"No INTERNET");
                             int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
                        }
                    }
                })
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .baseUrl(BASE_URL)
                .build();

        return retrofit;
    }
}

之后,我调用了api:

searchMovies("Titanic");

我得到结果。关闭wifi / 3g后,当我再次进行api调用时,我得到了Unable to resolve host "www.omdbapi.com" No adress assoicatied with hostname.

似乎它甚至不检查高速缓存中是否有任何东西,而只是尝试执行另一个请求,但是这次没有互联网。我有一个日志,可以在我通过互联网拨打电话时打印出响应标题,这是响应:

ORIGINAL RESPPONSE HEADERS {access-control-allow-origin=[*], cache-control=[public, max-age=86400], cf-cache-status=[HIT], cf-ray=[4c6ec52828bb9720-FRA], connection=[keep-alive], content-type=[application/json; charset=utf-8], date=[Sat, 13 Apr 2019 16:20:55 GMT], expires=[Sun, 14 Apr 2019 16:20:55 GMT], last-modified=[Fri, 12 Apr 2019 16:04:42 GMT], server=[cloudflare], set-cookie=[__cfduid=dad69c836be19bd3f9575cc59759f95d21555172455; expires=Sun, 12-Apr-20 16:20:55 GMT; path=/; domain=.omdbapi.com; HttpOnly], transfer-encoding=[chunked], vary=[*, Accept-Encoding], x-aspnet-version=[4.0.30319], x-powered-by=[ASP.NET]}

在没有互联网的情况下拨打电话时,上述代码中的任何日志都不会触发。

请注意,这是我在课堂上输入的内容:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

有什么想法吗?

0 个答案:

没有答案