有时候我们要对网络数据进行缓存默认情况下okhttp是不进行缓存的 添加拦截器进行数据拦截。 static OkHttpClient client; static { client = new OkHttpClient(); File cacheFile = null; client.newBuilder()//创建一个构建者 .readTimeout(15, TimeUnit.SECONDS)//设置读取的超时时间 .connectTimeout(15, TimeUnit.SECONDS)//设置连接的超时时间 .writeTimeout(15, TimeUnit.SECONDS)//设置读写超时时间 .addNetworkInterceptor(new CacheIntercepter())//添加网络拦截器 .cache(new Cache(cacheFile, 10 * 1024 * 1024)); } static class CacheIntercepter implements Interceptor { //服务端未做相关的cache缓存配置 @Override public Response intercept(Chain chain) throws IOException { Response response = chain.proceed(chain.request()); return response.newBuilder()//构造者 .removeHeader("pragma")//移除标题 .header("Cache-Control", "max-age=15") .build(); //设置缓存时间为60秒,并移除了pragma消息头,移除它的原因是因为pragma也是控制缓存的一个消息头属性 } }
关于OkHttp的缓存和网络拦截
最新推荐文章于 2023-08-06 08:54:05 发布