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;
                    }
                });
            }

      

  • 相关阅读:
    专业词汇-数学-运算:四则运算
    专业词汇-数学-运算:逆运算
    专业词汇-数学:运算
    DNF Package Management-CentOS 8
    Change the HostName of CentOS 8
    CentOS8 修改SSH端口,禁用root登录,修改SSH协议
    CentOS8 Disable IPV6 and Selinux
    Ubuntu 20.04 Install SSH, Change SSH Port, Enable root
    ubuntu 20.04 重启网卡服务
    Ubuntu 20.04 Install Guest Additions for VirtualBox
  • 原文地址:https://www.cnblogs.com/androidsuperman/p/5197458.html
Copyright © 2011-2022 走看看