背景
之前學習完Retrofit+Rxjava之后寫了一篇關于封裝的博客,發出后受到大家的關注以及使用,由于不斷的完善之前的項目,所以決定把最新的項目封裝過程講解出來,供大家查看!
Retrofit介紹:
Retrofit和okHttp師出同門,也是Square的開源庫,它是一個類型安全的網絡請求庫,Retrofit簡化了網絡請求流程,基于OkHtttp做了封裝,解耦的更徹底:比方說通過注解來配置請求參數,通過工廠來生成CallAdapter,Converter,你可以使用不同的請求適配器(CallAdapter), 比方說RxJava,Java8, Guava。你可以使用不同的反序列化工具(Converter),比方說json, protobuff, xml, moshi等等。
官網 http://square.github.io/retrofit/
github https://github.com/square/retrofit
效果
	
懶人簡單的使用方式
為什么稱為懶人,因為你什么都不用做,直接按照一般案例寫rx和retrofit的使用
引入需要的包
/*rx-android-java*/ compile 'io.reactivex:rxjava:+' 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<RetrofitEntity> 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);    Observable<RetrofitEntity> observable = apiService.getAllVedioBy(true);    observable.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())        .subscribe(            new Subscriber<RetrofitEntity>() {              @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();              }            }        );源碼:傳送門-源碼地址
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答