标签:else gradle str active ica htm tac 文件 square
Retrofit 是一个当前很流行的网络请求库
想使用它首先在gradle文件中引用
compile ‘com.squareup.retrofit2:retrofit:2.1.0‘ compile ‘com.squareup.retrofit2:adapter-rxjava:2.1.0‘ compile ‘com.squareup.retrofit2:converter-gson:2.0.2’
RxJava 是针对于Java语音的一个异步响应式编程库
compile ‘io.reactivex.rxjava2:rxjava:2.0.1‘
compile ‘io.reactivex.rxjava2:rxandroid:2.0.1’
Retrofit的使用
创建一个Retrofit对象
private static void initRetrofit() { sRetrofit = new Retrofit.Builder() .baseUrl("http://www.weather.com.cn/") .client(sOkHttpClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); }
client 设置OkHttp用于拦截器设置
addCallAdapterFactory()设置支持RxJava返回值为Oservable<M>
addConverterFactory() 设置支持Gson 直接返回实体类
接下来在创建一个OKHttpClient.Buildr对象
OkHttpClient.Builder builder = new OkHttpClient.Builder();
1设置结果拦截器
Interceptor cacheInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if (!CommonUtil.isNetworkConnected(MyApplication.getInstance())) { request = request.newBuilder() .cacheControl(CacheControl.FORCE_CACHE) .build(); } Response response = chain.proceed(request); Response.Builder newBuilder = response.newBuilder(); if (CommonUtil.isNetworkConnected(MyApplication.getInstance())) { int maxAge = 0; // 有网络时 设置缓存超时时间0个小时 newBuilder.header("Cache-Control", "public, max-age=" + maxAge); } else { // 无网络时,设置超时为4周 int maxStale = 60 * 60 * 24 * 28; newBuilder.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale); } return newBuilder.build(); } };
在这里有网络取最新,没网取缓存
builder.cache(cache).addInterceptor(cacheInterceptor);
添加到builder;
2.设置请求拦截器
Interceptor requestInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request() .newBuilder() .addHeader("Accept", "application/vnd.yu.v4+json") .addHeader("Content-Type", "application/json") .addHeader("Range", "page:1,max:10") .addHeader("Authorization", "") .build();request.headers().toString()); return chain.proceed(request); } };
一般设置统一header 时使用
builder.addNetworkInterceptor(requestInterceptor);
设置超时重连
builder.connectTimeout(15, TimeUnit.SECONDS); builder.readTimeout(20, TimeUnit.SECONDS); builder.writeTimeout(20, TimeUnit.SECONDS); builder.retryOnConnectionFailure(true);
return builder.build();
OkHttp设置完成。
接下来去设置ApiCallBack
使用RxJava订阅
ApiCallBack<M>是abstract要继承Subscriber<M>
public abstract class ApiCallback<M> extends Subscriber<M> { public abstract void onSuccess(M model); public abstract void onFailure(String msg); public abstract void onFinish(); @Override public void onError(Throwable e) { e.printStackTrace(); if (e instanceof HttpException) { HttpException httpException = (HttpException) e; int code = httpException.code(); String msg = httpException.getMessage(); if (code == 504) { msg = "网络不给力"; } if (code == 502 || code == 404) { msg = "服务器异常,请稍后再试"; } onFailure(msg); } else { onFailure(e.getMessage()); } onFinish(); } @Override public void onNext(M model) { onSuccess(model); } @Override public void onCompleted() { onFinish(); } }
接下来去写ApiService
ApiService 是个接口
Retrofit提供的请求方式用注解修改变量生成URL等
RxJava方式
@GET("adat/sk/{cityId}.html") Observable<MainModel> getMainBanner(@Path("cityId") String cityId); //请求方式@GET,@POST ,@PUT @DELETE 等。 (@Path(“cityId") String cityId) //修改路径中对应的变量{cityId} @POST Observable<MainModel> getTaskToken(@Url String url, @Body String body); @Headers({"Accept: application/json","Content-Type: application/json"}) @GET Observable<RecordsTask> getMainTask(@Url String url, @Header("Authorization") String token);
以上简单写了几种大多数都包括了
需要的已经配置好了 下面去使用它
//RXjava注册 public void addSubscription(Observable observable, Subscriber subscriber) { if (mCompositeSubscription == null) { mCompositeSubscription = new CompositeSubscription(); } mCompositeSubscription.add(observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(subscriber)); }
把上面内容写在Base中
subscribeOn() : 指定
subscribe()所发生的线程,即Observable.OnSubscribe被激活时所处的线程。或者叫做事件产生的线程。
observeOn():指定用户所运行的线程。或者叫做事件消费的线程。
使用 subscribeOn() 和 observeOn() 两个方法来对线程进行控制了。
在Activity中调用
public void loadWeather(String city) { addSubscription(mApiService.getMainBanner(city), new ApiCallback<MainModel>() { @Override public void onSuccess(MainModel response) { mMvpView.onSuccess(response); } @Override public void onFailure(String msg) { mMvpView.onFail(msg, 1); } @Override public void onFinish() { } }); }
在结束时还需要取消RxJava的注册以免内存泄漏
public void onUnsubscribe() { if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) { mCompositeSubscription.unsubscribe(); } }
结束。
标签:else gradle str active ica htm tac 文件 square
原文地址:http://www.cnblogs.com/teddy-yan/p/6923203.html