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; } }); }
时间: 2024-09-29 23:29:15