Okhttp設置http緩存,在沒有網絡的狀況下加載http緩存裏面的內容

HTTP_CACHE_FILENAME爲緩存地址根路徑;
private final        String      HTTP_CACHE_FILENAME               = "HttpCache";
    private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
        @Override public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder()
                                   .removeHeader("Pragma")
                                   .header("Cache-Control", String.format("max-age=%d", 60))
                                   .build();
        }
    };

 

而後再okhttpclient初始化的時候加上緩存設置:緩存

mOkHttpClient = new OkHttpClient();
        //cookie enabled
        mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
        mOkHttpClient.setConnectTimeout(15000, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(15000, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(15000, TimeUnit.SECONDS);
        mOkHttpClient.setRetryOnConnectionFailure(true);
        //-------------------------------設置http緩存,提高用戶體驗-----------------------------------
        Cache cache;
        File httpCacheDirectory = new File(BaseApplication.getAppContext().getExternalCacheDir(), HTTP_CACHE_FILENAME);
        cache = new Cache(httpCacheDirectory, 10 * 1024);
        mOkHttpClient.setCache(cache);
        mOkHttpClient.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
        //-------------------------------設置http緩存,提高用戶體驗-----------------------------------

        mDelivery = new Handler(Looper.getMainLooper());

        if (false) {
            mOkHttpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
相關文章
相關標籤/搜索