安卓RxJava+Retorfit+OKHttp完成对网络的基本

2020-03-08  本文已影响0人  Tyson_Wu

一,在APP的gradle下添加相关的依赖

     //retrofit
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    //rx
    implementation 'com.jakewharton.rxbinding2:rxbinding:2.0.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.6'

上述gradle包含了Gson自动转换,rxjava ,okhttp等封装所需依赖

二,需要封装一个NetManager的管理类,此类在项目初始化的地方进行初始化,调用NetManager.init();



//    private static String url = "http://eyetrain.holosz.com/";
    private static String url = "此处填写你的api的接口地址";

    private static Retrofit mRetrofit;

    public static void init() {

        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create(JsonUtil.GSON))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(getDefaultClient());

        mRetrofit = builder.build();

    }

    /**
     * 获取相应的服务
     *
     * @param service
     * @param <T>
     * @return
     */
    public static <T> T getService(Class<T> service) {
        return mRetrofit.create(service);
    }


    private static OkHttpClient getDefaultClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
        interceptor.setLevel(level);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .readTimeout(10000, TimeUnit.MILLISECONDS)
                .writeTimeout(10000, TimeUnit.MILLISECONDS)
                .addInterceptor(interceptor)
                .followRedirects(false)
                .retryOnConnectionFailure(true)
                .followSslRedirects(false);
        try {
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            return builder.build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder.build();
    }


}

三,需要封装一个NetHelper工具类,用于对网络情况进行判断

public class NetHelper {
    public static boolean isNetworkConnected() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) UIUtils.getContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
        return false;
    }


    public @interface RiskType {
    }

    /**
     * 没有连接网络
     */
    public static final int NETWORK_NONE = -1;
    /**
     * 移动网络
     */
    public static final int NETWORK_MOBILE = 0;
    /**
     * 无线网络
     */
    public static final int NETWORK_WIFI = 1;

    public static int getNetWorkState(Context context) {
        // 得到连接管理器对象
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {

            if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
                return NETWORK_WIFI;
            } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
                return NETWORK_MOBILE;
            }
        } else {
            return NETWORK_NONE;
        }
        return NETWORK_NONE;
    }


}

四、接下来就开始编写你的Rx相关部分

public class BaseApi {

    protected static Disposable subscribeOnUiThread(Observable observable, final OnHttpFinishListener listener) {
        if (!NetHelper.isNetworkConnected()) {
            ToastUtil.showShortTimeMsg("请检查网络设置");
            listener.onFail("请检查网络设置");
            return null;
        }
        return observable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .map(new HttpResultFunc())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpSuccessSubscriber(listener), new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        listener.onFail(throwable.getMessage());
                    }
                });
    }

    protected static Disposable subscribeOnUiThread1(Observable observable, final OnHttpFinishListener listener) {
        if (!NetHelper.isNetworkConnected()) {
            ToastUtil.showShortTimeMsg("请检查网络设置");
            listener.onFail("请检查网络设置");
            return null;
        }
        return observable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .map(new HttpResultFunc1())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpSuccessSubscriber(listener), new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        listener.onFail(throwable.getMessage());
                    }
                });
    }


}

五,封装你的retrofit相关接口(service)以及获取service的工具类

/**
 * @author tyson_wu
 * @date 2020/3/1
 * @description:
 */
public interface ChildrenService {

    @POST("addChildren")
    Observable<HttpResp<Children>> uploadChildren(@Body Children children);

    @POST("updateChildrenData")
    Observable<HttpResp<Children>> updateChildren(@Body Children children);

    @POST("getVisionData")
    Observable<HttpResp<List<VisionData>>> getVisionData(@Body GetVisionDataReq req);

    @POST("commitVisionData")
    Observable<HttpResp> commitVisionData(@Body VisionData req);
}

/**
 * @author tyson_wu
 * @date 2020/1/10
 * @description : 用于获取服务类
 */
public class Service {

    public static UserDataService getUserDataService() {
        return NetManager.getService(UserDataService.class);
    }

    public static OtherService getOtherService() {
        return NetManager.getService(OtherService.class);
    }

    public static ChildrenService getChildrenService() {
        return NetManager.getService(ChildrenService.class);
    }
}

六,封装你的各个presenter的api


public class LoginApi extends BaseApi {

    /**
     * 电话号码登录
     *
     * @param req
     * @param listener
     */
    public static void phoneLogin(LoginReq req, OnHttpFinishListener<User> listener) {
        subscribeOnUiThread(Service.getUserDataService().login(req), listener);
    }

    /**
     * 用户注册
     *
     * @param req
     * @param listener
     */
    public static void register(RegisterReq req, OnHttpFinishListener<User> listener) {
        subscribeOnUiThread(Service.getUserDataService().register(req), listener);
    }

    /**
     * 找回密码
     * @param req
     * @param listener
     */
    public static void forgotPassword(RegisterReq req, OnHttpFinishListener<User> listener) {
        subscribeOnUiThread(Service.getUserDataService().forgotPassword(req), listener);
    }
}

最后你就可以调用啦,在Presenter中进行网络调用,然后可以使用EventBus进行通讯,也可以利用View中的接口让Activity与Presenter进行通讯

上一篇下一篇

猜你喜欢

热点阅读