创建拦截器(Interceptor)
可以分开写两个拦截器一个有网的一个离线的,这里只写了一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() { @Override public okhttp3.Response intercept(Chain chain) throws IOException { okhttp3.Response originalResponse = chain.proceed(chain.request()); if (com.xuan.bledemo.util.Utils.isNetworkAvailable(MainActivity.this)) { int maxAge = 60; Log.i("缓存测试", "在线"); return originalResponse.newBuilder() .removeHeader("Pragma") .header("Cache-Control", "public,max-age=" + maxAge) .build(); } else { int maxStale = 60 * 60 * 24 * 28; Log.i("缓存测试", "离线"); return originalResponse.newBuilder() .removeHeader("Pragma") .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale) .build(); } } };
|
设置缓存文件
问题?关于缓存文件在手机上的地方,目前未找到
1 2 3 4
| File cacheFile=new File(this.getCacheDir(),"xuanCache"); Log.i("缓存测试","缓存目录"+this.getCacheDir().getPath()); Cache cache=new Cache(cacheFile,1024*1024*100);
|
创建httpclient
1 2 3 4 5 6 7 8
| OkHttpClient okHttpClient=new OkHttpClient.Builder() .cache(cache) .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR) .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR) .retryOnConnectionFailure(true) .connectTimeout(5, TimeUnit.SECONDS) .build();
|
将httpclient添加到retrofit
1 2 3 4 5 6
| Retrofit retrofit=new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .baseUrl("http://api.zdoz.net/") .build();
|
请求数据
第一次必须有网络,后面无网络就是请求缓存
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| Itest itest=retrofit.create(Itest.class); Call<Test> getCall= itest.getTest(108.2345); getCall.enqueue(new Callback<Test>() { @Override public void onResponse(Call<Test> call, Response<Test> response) { Log.e("缓存测试","请求成功"+response.body().getD()); } @Override public void onFailure(Call<Test> call, Throwable t) { Log.e("缓存测试","请求失败"+t.toString());
} });
|
问题,未验证
- 相当与数据库的 POST(创建)、PUT(更新)、GET(查看)、DELETE(删除)
- 缓存根据查找的资料,好像只有GET可以缓存
总结
- 上述缓存,是同一缓存的配置,如果要单个请求配置,可以设置接口的head,在里面传参数,然后在统一的缓存配置中用参数动态变化没次的不同缓存策略及时间。