背景
今年Android移动各大门户网站最热门的无非RxJava-Retrofit-OkHttp,所以准备强势入手一波封装,解决代码复用性的问题,这篇先先来个简单的压压惊,看看RxJava-Retrofit结合的使用基础要点,后续会出一些列的专栏优化一套完善的请求封装。
效果
懒人简单的使用方式
为什么称为懒人,因为你什么都不用做,直接按照一般案例写rx和retrofit的使用
- 引入需要的包
/*rx-android-java*/ compile 'com.squareup.retrofit:adapter-rxjava:+' compile 'com.trello:rxlifecycle:+' compile 'com.trello:rxlifecycle-components:+' /*rotrofit*/ compile 'com.squareup.retrofit2:retrofit:+' compile 'com.squareup.retrofit2:converter-gson:+' compile 'com.squareup.retrofit2:adapter-rxjava:+' compile 'com.google.code.gson:gson:+'复制代码
创建一个service定义请求的接口
/*** service统一接口数据* Created by WZG on 2016/7/16.*/public interface HttpService { @POST("AppFiftyToneGraph/videoLink") Observable
getAllVedioBy(@Body boolean once_no);}复制代码 创建一个retrofit对象
//手动创建一个OkHttpClient并设置超时时间 okhttp3.OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(5, TimeUnit.SECONDS); Retrofit retrofit = new Retrofit.Builder() .client(builder.build()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(HttpManager.BASE_URL) .build();复制代码
- http请求处理
// 加载框 final ProgressDialog pd = new ProgressDialog(this); HttpService apiService = retrofit.create(HttpService.class); Observableobservable = apiService.getAllVedioBy(true); observable.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe( new Subscriber () { @Override public void onCompleted() { if (pd != null && pd.isShowing()) { pd.dismiss(); } } @Override public void onError(Throwable e) { if (pd != null && pd.isShowing()) { pd.dismiss(); } } @Override public void onNext(RetrofitEntity retrofitEntity) { tvMsg.setText("无封装:\n" + retrofitEntity.getData().toString()); } @Override public void onStart() { super.onStart(); pd.show(); } } );复制代码