前言:Retrofit2+Rxjava2+Okhttp3的网络请求框架无疑是当前最流行的网络请求方式,retrofit负责请求的数据结果,rxjava负责线程间的调度,okhttp负责数据请求的过程,Retrofit2+Rxjava2+Okhttp3三者完美的切合使得其功能更加强大,简单记录下在项目中使用时的简单封装。
implementation 'io.reactivex.rxjava2:rxjava:2.1.13' implementation 'io.reactivex.rxjava2:rxandroid:2.0.2' implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.squareup.okhttp3:okhttp:3.10.0' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
/** * Created by ruancw on 2018/5/22. * 数据请求接口 */ public interface ApiService { //获取数据 @FormUrlEncoded @POST ObservablegetRemoteData(@Url String url, @FieldMap LinkedHashMap , String> map); //上传文件 @Multipart @FormUrlEncoded @POST Observable upLoadFile(@Url String url, @Part List file, @FieldMap LinkedHashMap , String> map); //文件下载 @Streaming @GET Observable downloadFile(@Url() String url); }
HttpResponse通用数据返回类:
/** * Created by ruancw on 2018/5/23. * 网络请求数据返回类 */ public class HttpResponse<T> { private String message; private int status; private T data; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
(1)单例模式创建retrofit
private Retrofit retrofit; public static HttpApiService getInstance() { return Singleton.instance; } private static class Singleton { private static HttpApiService instance = new HttpApiService(); } private HttpApiService(){ retrofit = new Retrofit.Builder() .baseUrl(ApiConstant.baseUrl)//基础url .addConverterFactory(GsonConverterFactory.create())//将返回的数据转为Gson .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加Rxjava的回调 .client(genericClient())//添加okHttpClient .build(); }
(2)创建okhttpClient
private OkHttpClient genericClient() { OkHttpClient httpClient = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间 .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException {//添加拦截器,可进行其他相关操作 Request request=chain.request(); request=request .newBuilder() .build(); return chain.proceed(request); } }) //okHttpClient log日志打印 .addInterceptor(new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY)) .build(); return httpClient; }(3)获取apiService实例
//通过retrofit获取ApiService实例 private ApiService getApiService() { return getService(ApiService.class); } private <T> T getService(Class<T> cls) { return retrofit.create(cls); }(4)定义接口调用方法
//获取网络数据 public Observable getRemoteData(String url, LinkedHashMap, String> map) { return getApiService().getRemoteData(url,map); } //上传文件 public Observable updateFile(String url, List file, LinkedHashMap , String> map) { return getApiService().upLoadFile(url,file,map); } //下载文件 public Observable downloadFile(String url) { return getApiService().downloadFile(url); }
/** * rxjava取消注册 */ public void unSubscribe(){ if (mCompositeDisposable != null) { mCompositeDisposable.dispose(); } } /** * rxjava进行注册 * @param disposable */ public void addSubscription(Disposable disposable) {//rxjava进行注册 if (mCompositeDisposable == null) { mCompositeDisposable= new CompositeDisposable(); } mCompositeDisposable.add(disposable); }
(1)定义Disposable通用类(RxJava2中新的名称)
/** * * @param observable 被观察者 * @param which 用于区分来自哪个请求 * @param onRequestListener 请求响应接口 * @param <T> data的数据类型 * @return Disposable */ public static <T> Disposable getDisposable(ObservableT>> observable, final String which, final IBaseModel.IOnRequestListener onRequestListener) { Disposable disposable=observable .subscribeOn(Schedulers.io())//子线程 .observeOn(AndroidSchedulers.mainThread())//主线程 .subscribe(new Consumer T>>() { @Override public void accept(HttpResponse<T> tHttpResponse) throws Exception { if (onRequestListener!=null&&tHttpResponse!=null){ onRequestListener.onRequestSuccess(tHttpResponse,which); } } }, new Consumer () { @Override public void accept(Throwable throwable) throws Exception { if (onRequestListener!=null){ ExceptionHandle.handleException(throwable); throwable.printStackTrace(); onRequestListener.onRequestFail(throwable); } } }); return disposable; }
(2)model中获取Disposable实例
@Override public <T> Disposable getObservable(ObservableT>> observable, String tag) { return DisposableUtils.getDisposable(observable,tag,onRequestListener); }
(3)presenter实例中注册rxjava
addSubscription(mModel.getObservable(HttpApiService.getInstance().getRemoteData(url,paramsMap),tag));
定义Disposable通用类方便每次调用,没有用onNext,onError,onComplete等方法实现。
不足之处,欢迎斧正,不胜感激!!!