zoukankan      html  css  js  c++  java
  • 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;
                    }
                });
            }

      

  • 相关阅读:
    P1242 新汉诺塔(hanio)
    P2878 [USACO07JAN]保护花朵Protecting the Flowers
    P2096 最佳旅游线路
    [P1363] 幻想迷宫
    在矩阵上跑最小生成树
    tarjan+topsort
    tarjan缩点
    【P3398]】仓鼠找sugar
    树形数组暴力
    解决跨域问题
  • 原文地址:https://www.cnblogs.com/androidsuperman/p/5197458.html
Copyright © 2011-2022 走看看