retrofit2 +rxjava封装

我们看看使用Retrofit+Rxjava需要哪些依赖(使用Android studio的小伙伴跟着我的脚步eclipse的兄弟看着办)

[java]  view plain  copy
  1. compile 'io.reactivex.rxjava2:rxjava:2.0.7'  
  2. compile 'io.reactivex.rxjava2:rxandroid:2.0.1'  
  3. compile 'com.squareup.retrofit2:retrofit:2.1.0'  
  4. compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'  
  5. compile 'com.squareup.retrofit2:converter-gson:2.1.0'  
  6. compile 'com.squareup.okhttp3:okhttp:3.5.0'  
  7. compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'  

我们要知道Retrofit是基于OKhttp实现的,那么我们要写一个Retrofit工具,命名为RetrofitFactory

    首先我们要创建一个 OKHttpClient对象            

[java]  view plain  copy
  1.  OkHttpClient mOkHttpClient=new OkHttpClient.Builder()  
  2. .connectTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)//设置连接超时时间  
  3. .readTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)//设置读取超时时间  
  4. .writeTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)//设置写入超时时间  
  5. .addInterceptor(InterceptorUtil.HeaderInterceptor())//添加其他拦截器  
  6. .addInterceptor(InterceptorUtil.LogInterceptor())//添加日志拦截器  
  7. .build(); 

为了代码的可读性我把拦截器提取到一个工具类为InterceptorUtil(不知道什么是拦截器的童鞋建议百度一下)里面有两个方法一个是打印日志拦截器的方法,一个是处理和拦截http请求的方法

[java]  view plain  copy
  1. package com.yr.example.http;  
  2.   
  3. import android.util.Log;  
  4.   
  5. import java.io.IOException;  
  6.   
  7. import okhttp3.Interceptor;  
  8. import okhttp3.Request;  
  9. import okhttp3.Response;  
  10. import okhttp3.logging.HttpLoggingInterceptor;  
  11.   
  12. /** 
  13.  * @author yemao 
  14.  * @date 2017/4/9 
  15.  * @description 拦截器工具类! 
  16.  */  
  17.   
  18. public class InterceptorUtil {  
  19.     public static String TAG="----";  
  20.     //日志拦截器  
  21.     public static HttpLoggingInterceptor LogInterceptor(){  
  22.         return new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {  
  23.             @Override  
  24.             public void log(String message) {  
  25.                 Log.w(TAG, "log: "+message );  
  26.             }  
  27.         }).setLevel(HttpLoggingInterceptor.Level.BODY);//设置打印数据的级别  
  28.     }  
  29.   
  30.     public static Interceptor HeaderInterceptor(){  
  31.       return   new Interceptor() {  
  32.             @Override  
  33.             public Response intercept(Chain chain) throws IOException {  
  34.                 Request mRequest=chain.request();  
  35.                 //在这里你可以做一些想做的事,比如token失效时,重新获取token  
  36.                 //或者添加header等等,PS我会在下一篇文章总写拦截token方法  
  37.                 return chain.proceed(mRequest);  
  38.             }  
  39.         };  
  40.   
  41.     }  
  42. }  
然后是创建一个Retrofit
[java]  view plain  copy
  1. Retrofit mRetrofit=new Retrofit.Builder()  
  2.         .baseUrl(HttpConfig.BASE_URL)//这个baseUrl是什么?比如一个接口为'http://baidu.com/xxx','http://baidu.com/'就可以为baseURL  
  3.         .addConverterFactory(GsonConverterFactory.create())//添加gson转换器  
  4.         .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava转换器  
  5.         .client(mOkHttpClient)//传入上面创建的OKHttpClient  
  6.         .build();  
ok创建好Retrofit我们需要创建一个接口APIFunction类与之关联
[java]  view plain  copy
  1. package com.yr.example.http;  
  2.   
  3. import com.yr.example.http.bean.BaseEntity;  
  4. import com.yr.example.http.config.URLConfig;  
  5.   
  6. import io.reactivex.Observable;  
  7. import retrofit2.http.GET;  
  8. import retrofit2.http.Query;  
  9.   
  10. /** 
  11.  * @author yemao 
  12.  * @date 2017/4/9 
  13.  * @description API接口! 
  14.  */  
  15.   
  16. public interface APIFunction {  
  17.   
  18.       
  19. }  
终于可以看到我们完整的工具类RetrofitFactory了     
[java]  view plain  copy
  1. package com.yr.example.http;  
  2.   
  3. import com.yr.example.http.config.HttpConfig;  
  4.   
  5. import java.util.concurrent.TimeUnit;  
  6.   
  7. import okhttp3.OkHttpClient;  
  8. import retrofit2.Retrofit;  
  9. import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;  
  10. import retrofit2.converter.gson.GsonConverterFactory;  
  11.   
  12. /** 
  13.  * @author yemao 
  14.  * @date 2017/4/9 
  15.  * @description 写自己的代码, 让别人说去吧! 
  16.  */  
  17.   
  18. public class RetrofitFactory {  
  19.   
  20.     private static RetrofitFactory mRetrofitFactory;  
  21.     private static  APIFunction mAPIFunction;  
  22.     private RetrofitFactory(){  
  23.         OkHttpClient mOkHttpClient=new OkHttpClient.Builder()  
  24.                 .connectTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)  
  25.                 .readTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)  
  26.                 .writeTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)  
  27.                 .addInterceptor(InterceptorUtil.HeaderInterceptor())  
  28.                 .addInterceptor(InterceptorUtil.LogInterceptor())//添加日志拦截器  
  29.                 .build();  
  30.         Retrofit mRetrofit=new Retrofit.Builder()  
  31.                 .baseUrl(HttpConfig.BASE_URL)  
  32.                 .addConverterFactory(GsonConverterFactory.create())//添加gson转换器  
  33.                 .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava转换器  
  34.                 .client(mOkHttpClient)  
  35.                 .build();  
  36.         mAPIFunction=mRetrofit.create(APIFunction.class);  
  37.   
  38.     }  
  39.   
  40.     public static RetrofitFactory getInstence(){  
  41.         if (mRetrofitFactory==){  
  42.             synchronized (RetrofitFactory.class) {  
  43.                 if (mRetrofitFactory == )  
  44.                     mRetrofitFactory = new RetrofitFactory();  
  45.             }  
  46.   
  47.         }  
  48.         return mRetrofitFactory;  
  49.     }  
  50.     public  APIFunction API(){  
  51.         return mAPIFunction;  
  52.     }  
  53. }  
接下来我们就要开始接口了哦,回到我们上面的APIFunction接口模拟一个API接口getBaidu()因为上面我们已经对Retrofit和 APIFunction进行关联了可以返回得到 一个observable<Object>(终于轮到Rxjava出场了)
[java]  view plain  copy
  1. package com.yr.example.http;  
  2.   
  3. import com.yr.example.http.bean.BaseEntity;  
  4. import com.yr.example.http.config.URLConfig;  
  5.   
  6. import io.reactivex.Observable;  
  7. import retrofit2.http.GET;  
  8. import retrofit2.http.Query;  
  9.   
  10. /** 
  11.  * @author yemao 
  12.  * @date 2017/4/9 
  13.  * @description API接口! 
  14.  */  
  15.   
  16. public interface APIFunction {  
  17.   
  18.     @GET(URLConfig.baidu_url)  
  19.     Observable<Object> getBaidu(@Query("wd")String name);  
  20. }  

额看到这里我们怎么让它返回一个对象实体,不能让它返回我们想要的实体类吗,答案是yes,OK那我们来封装一个BaseEntity

当然我这只是举例个例子,很有可能大家的返回参数不是按照下面的,(因实际情况做修改)

[java]  view plain  copy
  1. package com.yr.example.http.bean;  
  2.   
  3. /** 
  4.  * @author yemao 
  5.  * @date 2017/4/9 
  6.  * @description 解析实体基类! 
  7.  */  
  8.   
  9. public class BaseEntity<T> {  
  10.     private static int SUCCESS_CODE=0;//成功的code  
  11.     private int code;  
  12.     private String msg;  
  13.     private T data;  
  14.   
  15.   
  16.     public boolean isSuccess(){  
  17.         return getCode()==SUCCESS_CODE;  
  18.     }  
  19.     public int getCode() {  
  20.         return code;  
  21.     }  
  22.   
  23.     public void setCode(int code) {  
  24.         this.code = code;  
  25.     }  
  26.   
  27.     public String getMsg() {  
  28.         return msg;  
  29.     }  
  30.   
  31.     public void setMsg(String msg) {  
  32.         this.msg = msg;  
  33.     }  
  34.   
  35.     public T getData() {  
  36.         return data;  
  37.     }  
  38.   
  39.     public void setData(T data) {  
  40.         this.data = data;  
  41.     }  
  42.   
  43. }  

我们看看修改过后的接口是怎么样的

[java]  view plain  copy
  1. @GET(URLConfig.baidu_url)  
  2.    Observable<BaseEntity<Object>> getBaidu(@Query("wd")String name); 

当然这是候的Object可以换为你想要的实体比如(前提是你要知道返回的数据类型我这只是打个比方)

[java]  view plain  copy
  1. package com.yr.example.http.bean;  
  2.   
  3. /** 
  4.  * @author yemao 
  5.  * @date 2017/4/9 
  6.  * @description 写自己的代码, 让别人说去吧! 
  7.  */  
  8.   
  9. public class ABean {  
  10.     private String name;  
  11.     private String pwd;  
  12.   
  13.     public String getName() {  
  14.         return name;  
  15.     }  
  16.   
  17.     public void setName(String name) {  
  18.         this.name = name;  
  19.     }  
  20.   
  21.     public String getPwd() {  
  22.         return pwd;  
  23.     }  
  24.   
  25.     public void setPwd(String pwd) {  
  26.         this.pwd = pwd;  
  27.     }  
  28. }  

把object替换为ABean

[java]  view plain  copy
  1. @GET(URLConfig.baidu_url)  
  2.  Observable<BaseEntity<ABean>> getBaidu(@Query("wd")String name);  

OK这时候就可以跑通了让我们看看完整的请求 (observable(被观察者)和observer(观察者)相订阅)

[java]  view plain  copy
  1. RetrofitFactory.getInstence().API()  
  2.                .getBaidu("我是中国人")  
  3.                .subscribeOn(Schedulers.io())  
  4.                .observeOn(AndroidSchedulers.mainThread())  
  5.                .subscribe(new Observer<BaseEntity<ABean>>() {  
  6.                    @Override  
  7.                    public void onSubscribe(Disposable d) {  
  8.                          
  9.                    }  
  10.   
  11.                    @Override  
  12.                    public void onNext(BaseEntity<ABean> aBeanBaseEntity) {  
  13.   
  14.                    }  
  15.   
  16.                    @Override  
  17.                    public void onError(Throwable e) {  
  18.   
  19.                    }  
  20.   
  21.                    @Override  
  22.                    public void onComplete() {  
  23.   
  24.                    }  
  25.                });  
可以发现还有地方可以优化比如Observable线程的切换,以及Observer的封装,不废话了我们先封装一个BaseObserver

BaseObserver实现了Observer接口,然后添加了5个方法

[java]  view plain  copy
  1. onRequestStart 请求开始时调用  
[java]  view plain  copy
  1. onRequestEnd 请求结束时调用  
[java]  view plain  copy
  1. onFailure 请求失败时调用   
[java]  view plain  copy
  1. onSuccees  请求成功时调用  
[java]  view plain  copy
  1. onCodeError 请求成功但code码错误时调用  

然后完整的BaseObserve

[java]  view plain  copy
  1. package com.yr.example.http.base;  
  2.   
  3. import android.accounts.NetworkErrorException;  
  4. import android.content.Context;  
  5. import android.util.Log;  
  6.   
  7. import com.yr.example.http.bean.BaseEntity;  
  8. import com.yr.example.widget.ProgressDialog;  
  9.   
  10. import java.net.ConnectException;  
  11. import java.net.UnknownHostException;  
  12. import java.util.concurrent.TimeoutException;  
  13.   
  14. import io.reactivex.Observer;  
  15. import io.reactivex.disposables.Disposable;  
  16.   
  17. /** 
  18.  * @author yemao 
  19.  * @date 2017/4/9 
  20.  * @description 写自己的代码, 让别人说去吧! 
  21.  */  
  22.   
  23. public abstract class BaseObserver<T> implements Observer<BaseEntity<T>> {  
  24.     protected Context mContext;  
  25.   
  26.     public BaseObserver(Context cxt) {  
  27.         this.mContext = cxt;  
  28.     }  
  29.   
  30.     public BaseObserver() {  
  31.   
  32.     }  
  33.   
  34.     @Override  
  35.     public void onSubscribe(Disposable d) {  
  36.         onRequestStart();  
  37.   
  38.     }  
  39.   
  40.     @Override  
  41.     public void onNext(BaseEntity<T> tBaseEntity) {  
  42.         onRequestEnd();  
  43.         if (tBaseEntity.isSuccess()) {  
  44.             try {  
  45.                 onSuccees(tBaseEntity);  
  46.             } catch (Exception e) {  
  47.                 e.printStackTrace();  
  48.             }  
  49.         } else {  
  50.             try {  
  51.                 onCodeError(tBaseEntity);  
  52.             } catch (Exception e) {  
  53.                 e.printStackTrace();  
  54.             }  
  55.         }  
  56.     }  
  57.   
  58.     @Override  
  59.     public void onError(Throwable e) {  
  60. //        Log.w(TAG, "onError: ", );这里可以打印错误信息  
  61.         onRequestEnd();  
  62.         try {  
  63.             if (e instanceof ConnectException  
  64.                     || e instanceof TimeoutException  
  65.                     || e instanceof NetworkErrorException  
  66.                     || e instanceof UnknownHostException) {  
  67.                 onFailure(e, true);  
  68.             } else {  
  69.                 onFailure(e, false);  
  70.             }  
  71.         } catch (Exception e1) {  
  72.             e1.printStackTrace();  
  73.         }  
  74.     }  
  75.   
  76.     @Override  
  77.     public void onComplete() {  
  78.     }  
  79.   
  80.     /** 
  81.      * 返回成功 
  82.      * 
  83.      * @param t 
  84.      * @throws Exception 
  85.      */  
  86.     protected abstract void onSuccees(BaseEntity<T> t) throws Exception;  
  87.   
  88.     /** 
  89.      * 返回成功了,但是code错误 
  90.      * 
  91.      * @param t 
  92.      * @throws Exception 
  93.      */  
  94.     protected void onCodeError(BaseEntity<T> t) throws Exception {  
  95.     }  
  96.   
  97.     /** 
  98.      * 返回失败 
  99.      * 
  100.      * @param e 
  101.      * @param isNetWorkError 是否是网络错误 
  102.      * @throws Exception 
  103.      */  
  104.     protected abstract void onFailure(Throwable e, boolean isNetWorkError) throws Exception;  
  105.   
  106.     protected void onRequestStart() {  
  107.     }  
  108.   
  109.     protected void onRequestEnd() {  
  110.         closeProgressDialog();  
  111.     }  
  112.   
  113.     public void showProgressDialog() {  
  114.         ProgressDialog.show(mContext, false"请稍后");  
  115.     }  
  116.   
  117.     public void closeProgressDialog() {  
  118.         ProgressDialog.cancle();  
  119.     }  
  120.   
  121. }  
然后我们看看完整的请求
[java]  view plain  copy
  1. RetrofitFactory.getInstence().API()  
  2.              .getBaidu("我是中国人")  
  3.              .subscribeOn(Schedulers.io())  
  4.              .observeOn(AndroidSchedulers.mainThread())  
  5.              .subscribe(new BaseObserver<ABean>() {  
  6.                  @Override  
  7.                  protected void onSuccees(BaseEntity<ABean> t) throws Exception {  
  8.   
  9.                  }  
  10.   
  11.                  @Override  
  12.                  protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {  
  13.   
  14.                  }  
  15.              });  
是不是少了许多代码,最后我们将线程切换提成一个方法,放在一个新建的baseActivity里面让所有activity都继承自它,就都可以拿到这个方法了
[java]  view plain  copy
  1. package com.yr.example.common;  
  2.   
  3. import android.support.v4.app.FragmentActivity;  
  4.   
  5. import io.reactivex.Observable;  
  6. import io.reactivex.ObservableSource;  
  7. import io.reactivex.ObservableTransformer;  
  8. import io.reactivex.android.schedulers.AndroidSchedulers;  
  9. import io.reactivex.schedulers.Schedulers;  
  10.   
  11. /** 
  12.  * @author yemao 
  13.  * @date 2017/4/9 
  14.  * @description 写自己的代码, 让别人说去吧! 
  15.  */  
  16.   
  17. public class BaseActivity extends FragmentActivity {  
  18.     public <T> ObservableTransformer<T,T> setThread(){  
  19.        return new ObservableTransformer<T,T>() {  
  20.             @Override  
  21.             public ObservableSource<T>  apply(Observable<T>  upstream) {  
  22.                 return upstream.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());  
  23.             }  
  24.         };  
  25.     }  
  26.   
  27. }  

最后看看完成的请求

[html]  view plain  copy
  1. package com.yr.example;  
  2.   
  3. import android.support.v7.app.AppCompatActivity;  
  4. import android.os.Bundle;  
  5. import android.util.Log;  
  6.   
  7. import com.yr.example.common.BaseActivity;  
  8. import com.yr.example.http.RetrofitFactory;  
  9. import com.yr.example.http.base.BaseObserver;  
  10. import com.yr.example.http.bean.ABean;  
  11. import com.yr.example.http.bean.BaseEntity;  
  12.   
  13. import io.reactivex.Observer;  
  14. import io.reactivex.android.schedulers.AndroidSchedulers;  
  15. import io.reactivex.disposables.Disposable;  
  16. import io.reactivex.schedulers.Schedulers;  
  17.   
  18. public class MainActivity extends BaseActivity {  
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.activity_main);  
  24.         getData();  
  25.     }  
  26.   
  27.     public void getData() {  
  28.         RetrofitFactory.getInstence().API()  
  29.                 .getBaidu("我是中国人")  
  30.                 .compose(this.<BaseEntity<ABean>>setThread())  
  31.                 .subscribe(new BaseObserver<ABean>() {  
  32.                     @Override  
  33.                     protected void onSuccees(BaseEntity<ABean> t) throws Exception {  
  34.   
  35.                     }  
  36.   
  37.                     @Override  
  38.                     protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {  
  39.   
  40.                     }  
  41.                 });  
  42.     }  
  43. }  
最后贴一下项目目录结构

猜你喜欢

转载自blog.csdn.net/qq_42081816/article/details/80628301