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

      

  • 相关阅读:
    PL/SQL中判断字段为空
    ArrayList知识详解
    那些碰到过的异常
    Java中的==和equals( )方法
    String,StringBuilder和StringBuffer
    树莓派3b+_32位linux系统arm架构安装JDK
    [杂]右键拷贝文件路径
    [023]模板成员函数为什么不能是虚函数
    [杂]几个好玩的网址
    [022]c++虚函数、多态性与虚表
  • 原文地址:https://www.cnblogs.com/androidsuperman/p/5197458.html
Copyright © 2011-2022 走看看