所需的依赖
implementation 'com.google.code.gson:gson:2.8.5'//不用可以不加
implementation 'com.android.support:design:26.1.0'//不用可以不加
implementation 'com.squareup.okhttp3:okhttp:3.10.0'//新版本//不用可以不加
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'io.reactivex:rxjava:1.1.6'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
public interface ApiService {
@GET("1")
rx.Observable<Bean>getRx();
}
//普通缓存拦截器
private OkHttpClient getCache(Context context) {
final Cache ch = new Cache(new File(context.getCacheDir(), "ch"), 10240 * 1024);
return new OkHttpClient.Builder().cache(ch).addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request build = chain.request()
.newBuilder()
.cacheControl(new CacheControl.Builder()
//缓存可以停留的时间
.maxStale(2,TimeUnit.HOURS).build()).build();
return chain.proceed(build);
}
}).build();
}
//使用方式
new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://gank.io/api/data/%E7%A6%8F%E5%88%A9/40/")
.client(getCache(getActivity()))
.build()
.create(ApiService.class)
.getRx()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Bean>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (null != e) {
Log.d("BlankFragment", e.getMessage());
}
}
@Override
public void onNext(Bean bean) {
}
});