Android网络框架之Retrofit+RxJava+OkHttp

自己简单封装的网络请求框架,适合快速开发

在项目(Module)的build.gradle中添加依赖

 /** rxjava **/
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'io.reactivex.rxjava2:rxjava:2.1.9'

/** retrofit **/
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

/**  okhttp  **/
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'

Retrofit的管理类

import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitFactory {
    private HttpApi httpApi;

    //单例 饿汉模式
    private static class SingletonHolder {
        private static RetrofitFactory retrofitFactory = new RetrofitFactory();
    }

    public static RetrofitFactory getInstance() {
        return SingletonHolder.retrofitFactory;
    }

    private RetrofitFactory() {
        // 创建 OKHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(15, TimeUnit.SECONDS);//连接超时时间
        builder.writeTimeout(15, TimeUnit.SECONDS);//写操作 超时时间
        builder.readTimeout(15, TimeUnit.SECONDS);//读操作超时时间
        builder.retryOnConnectionFailure(true);//错误重连

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://www.wanandroid.com/")
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        httpApi = retrofit.create(HttpApi.class);
    }

    private  void toSubscribe(Observable observable, BaseObserver observer) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    public void getChapters(BaseObserver observer) {
        toSubscribe(httpApi.getChapters(), observer);
    }
}

HttpApi

import io.reactivex.Observable;
import retrofit2.http.GET;

public interface HttpApi {
    @GET("wxarticle/chapters/json ")
    Observable getChapters();
}

BaseObserver

import android.app.ProgressDialog;
import android.content.Context;
import com.fly.zhao.http.bean.BaseResponseEntity;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLHandshakeException;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

public abstract class BaseObserver implements Observer {
    private ProgressDialog progressDialog;

    /**
     * @param context 上下文
     */
    public BaseObserver(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("加载中...");
    }

    private void showProgressDialog() {
        if (progressDialog != null) {
            progressDialog.show();
        }
    }

    private void dismissProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onSubscribe(Disposable d) {
        showProgressDialog();
    }

    @Override
    public void onNext(T response) {
        if (response.success()) {
            try {
                onSuccess(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                onFailing(response.getErrorMsg());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        try {
            if (e instanceof SocketTimeoutException) {
                onFailing("请求超时");
            } else if (e instanceof ConnectException) {
                onFailing("网络连接超时");
            } else if (e instanceof SSLHandshakeException) {
                onFailing("安全证书异常");
            } else if (e instanceof HttpException) {//请求的地址不存在
                if (((HttpException) e).code() == 504) {
                    onFailing("网络异常,请检查您的网络状态");
                } else if (((HttpException) e).code() == 404) {
                    onFailing("请求的地址不存在");
                } else {
                    onFailing("请求失败");
                }
            } else if (e instanceof UnknownHostException) {
                onFailing("域名解析失败");
            } else {
                onFailing("error:" + e.getMessage());
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            dismissProgressDialog();
            progressDialog = null;
        }
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
    }

    public abstract void onSuccess(T response);

    public abstract void onFailing(String message);
}

BaseResponseEntity

public class BaseResponseEntity implements Serializable {
    private int errorCode;
    private String errorMsg;

    public boolean success() {
        return 0 == errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }
}

调用

  RetrofitFactory.getInstance().getChapters(new BaseObserver(LoginActivity.this) {
                @Override
                public void onSuccess(BaseResponseEntity response) {
                   
                }

                @Override
                public void onFailing(String message) {

                }
            });

可以在此基础上进行进一步封装。

你可能感兴趣的:(Android网络框架之Retrofit+RxJava+OkHttp)