retrofit 缓存设置
CacheInterceport
public class CacheInterceport implements Interceptor {
Context context;
final static int maxStale = 7 * 24 * 60;//分钟
int maxAge = 6;//分钟
public CacheInterceport(Context context) {
this.context = context;
}
public CacheInterceport(Context context, int maxAgeOnline, int maxScaleOffline) {
this.context = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (checkNet(context)) {
Response response = chain.proceed(request);
int maxAge = 6;
return response.newBuilder()
.removeHeader("Pragma")
.removeHeader("Cache-Control")
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
} else {
Log.e("yjbo-cache", "离线时缓存时间设置");
request = request.newBuilder()
.cacheControl(FORCE_CACHE1)
.build();
Response response = chain.proceed(request);
//下面注释的部分设置也没有效果,因为在上面已经设置了
return response.newBuilder()
.build();
}
}
//这是设置在多长时间范围内获取缓存里面,缓存一周
public static final CacheControl FORCE_CACHE1 = new CacheControl.Builder()
.onlyIfCached()
.maxStale(maxStale, TimeUnit.MINUTES)
.build();
}
配置okhttp及retrofit
/***
* 获取服务器数据
*/
private void initGet() {
//设置缓存
File httpCacheDirectory = new File(Environment.getExternalStorageDirectory(), "cache_responses_yjbo");
Cache cache = null;
try {
cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
} catch (Exception e) {
Log.e("OKHttp", "Could not create http cache", e);
}
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Interceptor cacheInterceptor = new CacheInterceport(this);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cache(cache)
.addInterceptor(cacheInterceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HttpService.baseHttp)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();
final HttpService service = retrofit.create(HttpService.class);
service.getRxUrl("http://lbs.sougu.net.cn/app.php?m=souguapp&c=appusers&a=network").subscribeOn(Schedulers.io())
.compose(new ErrorTransform<ResponseBody>())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ResponseBody>() {
@Override
public void onCompleted() {
Log.e("XXX", "onCompleted");
}
@Override
public void onError(Throwable e) {
Log.e("XXX", "onError");
showResult.setText("onError");
}
@Override
public void onNext(ResponseBody responseBody) {
Log.e("XXX", "onResponse" + "-");
try {
String result = responseBody.string();
showResult.setText(result);
Log.e("XXX", "onResponse" + "-" + result);
} catch (Exception e) {
Log.e("XXX", "error");
}
}
});
}