1. 程式人生 > >Android網路請求Retrofit2+Rxjava2+Okhttp3的簡單封裝

Android網路請求Retrofit2+Rxjava2+Okhttp3的簡單封裝

前言:Retrofit2+Rxjava2+Okhttp3的網路請求框架無疑是當前最流行的網路請求方式,retrofit負責請求的資料結果,rxjava負責執行緒間的排程,okhttp負責資料請求的過程,Retrofit2+Rxjava2+Okhttp3三者完美的切合使得其功能更加強大,簡單記錄下在專案中使用時的簡單封裝。

1.匯入依賴

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'

2.ApiService介面

/**
 * Created by ruancw on 2018/5/22.
 * 資料請求介面
 */
public interface 
ApiService { //獲取資料 @FormUrlEncoded @POST Observable<HttpResponse> getRemoteData(@Url String url, @FieldMap LinkedHashMap<String, String> map); //上傳檔案 @Multipart @FormUrlEncoded @POST Observable<HttpResponse> upLoadFile(@Url String url, @Part List<MultipartBody.Part> file,
@FieldMap LinkedHashMap<String, String> map);   //檔案下載 @Streaming @GET Observable<ResponseBody> 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;
}

}

3.HttpApiService網路請求類

(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, String> map) {
    return getApiService().getRemoteData(url,map);
}
//上傳檔案
public  Observable updateFile(String url, List<MultipartBody.Part> file, LinkedHashMap<String, String> map) {
    return getApiService().upLoadFile(url,file,map);
}

//下載檔案
public  Observable downloadFile(String url) {
    return getApiService().downloadFile(url);
}

4.定義Rxjava的註冊與反註冊方法

/**
 * 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);
}

5.presenter實體類中呼叫

(1)定義Disposable通用類(RxJava2中新的名稱)

/**
 * 
 * @param observable 被觀察者
 * @param which 用於區分來自哪個請求
 * @param onRequestListener 請求響應介面
 * @param <T> data的資料型別
 * @return Disposable
 */
public  static  <T> Disposable getDisposable(Observable<HttpResponse<T>> observable, final String which, final IBaseModel.IOnRequestListener onRequestListener) {
    Disposable disposable=observable
            .subscribeOn(Schedulers.io())//子執行緒
.observeOn(AndroidSchedulers.mainThread())//主執行緒
.subscribe(new Consumer<HttpResponse<T>>() {
                @Override
public void accept(HttpResponse<T> tHttpResponse) throws Exception {
                    if (onRequestListener!=null&&tHttpResponse!=null){
                        onRequestListener.onRequestSuccess(tHttpResponse,which);
}
                }

            }, new Consumer<Throwable>() {
                @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(Observable<HttpResponse<T>> 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等方法實現。

不足之處,歡迎斧正,不勝感激!!!