Android Retrofit2和Rxjava2的使用

Retrofit2和Rxjava2的使用

    • 添加依赖
    • 编写Retrofit工具类
    • 编写api
    • 编写请求实体类
    • 编写网络返回管理类
    • 使用

添加依赖

    api "io.reactivex.rxjava2:rxjava:2.1.0" // 必要rxjava2依赖
    api "io.reactivex.rxjava2:rxandroid:2.0.1" // 必要rxandrroid依赖,切线程时需要用到
    api 'com.squareup.retrofit2:retrofit:2.3.0' // 必要retrofit依赖
    api 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' // 必要依赖,和Rxjava结合必须用到,下面会提到
    api 'com.squareup.retrofit2:converter-gson:2.3.0' // 必要依赖,解析json字符所用
    api 'com.squareup.okhttp3:logging-interceptor:3.8.1' //非必要依赖, log依赖,如果需要打印OkHttpLog需要添加

编写Retrofit工具类

  • 编写单例模式
  • 编写日志拦截器
  • 使用OkHttoClient配置网络请求相关信息
  • 添加Rxjava监听数据返回
  • 添加Gson转换器
   package com.weiqun.cherytelematic.network;

import com.weiqun.cherytelematic.BuildConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author DcotorWei
 * @date :2019/11/25 10:09
 * @description :TODO
 * @email :[email protected]
 */
public class RetrifitUtil {
    private static RetrifitUtil retrifitUtil;
    public static RetrifitUtil getInstance() {
        if (retrifitUtil == null) {
            synchronized (RetrifitUtil.class) {
                if (retrifitUtil == null) {
                    retrifitUtil = new RetrifitUtil();
                }
            }
        }
        return retrifitUtil;
    }
    public Retrofit getRetrofit(String baseUrl){
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//返回Observer对象
                .addConverterFactory(GsonConverterFactory.create())//将Observer对象转化成相应的实体
                .client(getOkHttpClient())
                .build();
        return retrofit;
    }
    private OkHttpClient getOkHttpClient(){
        OkHttpClient okHttpClient=new OkHttpClient.Builder()
                .readTimeout(10000, TimeUnit.SECONDS)
                .writeTimeout(10000,TimeUnit.SECONDS)
                .connectTimeout(10000,TimeUnit.SECONDS)
                .addNetworkInterceptor(getIntercepter())//添加日志拦截器
                .build();
        return okHttpClient;
    }
    private Interceptor getIntercepter(){
        HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor();
        interceptor.setLevel(BuildConfig.DEBUG?HttpLoggingInterceptor.Level.BODY:HttpLoggingInterceptor.Level.NONE);
        return interceptor;
    }

}

编写api

api:此处使用百度错误的api,请自行配置

  /**
 * @author DcotorWei
 * @date :2019/11/25 10:42
 * @description :API接口文档
 * @email :[email protected]
 */
public interface CheryApi {
    String BASE_URL="http://cloudrive.baidu.cn/baidu/app/";
    String LOGIN="login";
}

编写请求实体类

实体类:
请求实体类可以自行配置
响应实体可以自行配置

package com.weiqun.cherytelematic.bean;

/**
 * @author DcotorWei
 * @date :2019/11/25 8:52
 * @description :TODO
 * @email :[email protected]
 */
public class UserBean {
    /**
     * version : 版本号
     * businessId :
     * serviceType :
     * globalId : 登录时可以传空字符串
     * requestId : 请求id
     * login : {"userAccount":"登录账号","userPasswd":"登录密码"}
     */

    private String version;
    private String businessId;
    private String serviceType;
    private String globalId;
    private String requestId;
    private LoginBean login;

    public UserBean(String version, String businessId, String serviceType, String globalId, String requestId, LoginBean login) {
        this.version = version;
        this.businessId = businessId;
        this.serviceType = serviceType;
        this.globalId = globalId;
        this.requestId = requestId;
        this.login = login;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getBusinessId() {
        return businessId;
    }

    public void setBusinessId(String businessId) {
        this.businessId = businessId;
    }

    public String getServiceType() {
        return serviceType;
    }

    public void setServiceType(String serviceType) {
        this.serviceType = serviceType;
    }

    public String getGlobalId() {
        return globalId;
    }

    public void setGlobalId(String globalId) {
        this.globalId = globalId;
    }

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public LoginBean getLogin() {
        return login;
    }

    public void setLogin(LoginBean login) {
        this.login = login;
    }

    public static class LoginBean {
        public LoginBean() {
        }

        public LoginBean(String userAccount, String userPasswd) {
            this.userAccount = userAccount;
            this.userPasswd = userPasswd;
        }

        /**
         * userAccount : 登录账号
         * userPasswd : 登录密码
         */

        private String userAccount;
        private String userPasswd;

        public String getUserAccount() {
            return userAccount;
        }

        public void setUserAccount(String userAccount) {
            this.userAccount = userAccount;
        }

        public String getUserPasswd() {
            return userPasswd;
        }
        public void setUserPasswd(String userPasswd) {
            this.userPasswd = userPasswd;
        }
    }
}

package com.weiqun.cherytelematic.bean.res;

import com.weiqun.cherytelematic.bean.BaseBean;

/**
 * @author DcotorWei
 * @date :2019/11/25 10:48
 * @description :TODO
 * @email :[email protected]
 */
public class LoginRes extends BaseBean {

    /**
     * userInfo : {"username":"1064611374687","password":"123456","email":null,"vin":"LVVDC17B2HD186057"}
     * vehicleInfo : {"vin":"LVVDC17B2HD186057","licenseNum":null,"vehicleType":"M1AEV","vehicleStyle":null,"iccid":"89860616010055022236"}
     * versionInfo : {"versionFlag":"","newVersion":"","versionRemark":"","versionUrl":""}
     * configInfo : {"pollInterval":600,"controlPollInterval":5,"timeout":105}
     * version : ver2.4.114
     * businessId : 100
     * serviceType : 601
     * globalId : 76a966b0-1dfd-4a4c-b640-82473581af35
     * resultCode : 0200
     */

    private UserInfoBean userInfo;
    private VehicleInfoBean vehicleInfo;
    private VersionInfoBean versionInfo;
    private ConfigInfoBean configInfo;
    private String version;
    private String businessId;
    private String serviceType;
    private String globalId;
    private String resultCode;

    public UserInfoBean getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(UserInfoBean userInfo) {
        this.userInfo = userInfo;
    }

    public VehicleInfoBean getVehicleInfo() {
        return vehicleInfo;
    }

    public void setVehicleInfo(VehicleInfoBean vehicleInfo) {
        this.vehicleInfo = vehicleInfo;
    }

    public VersionInfoBean getVersionInfo() {
        return versionInfo;
    }

    public void setVersionInfo(VersionInfoBean versionInfo) {
        this.versionInfo = versionInfo;
    }

    public ConfigInfoBean getConfigInfo() {
        return configInfo;
    }

    public void setConfigInfo(ConfigInfoBean configInfo) {
        this.configInfo = configInfo;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getBusinessId() {
        return businessId;
    }

    public void setBusinessId(String businessId) {
        this.businessId = businessId;
    }

    public String getServiceType() {
        return serviceType;
    }

    public void setServiceType(String serviceType) {
        this.serviceType = serviceType;
    }

    public String getGlobalId() {
        return globalId;
    }

    public void setGlobalId(String globalId) {
        this.globalId = globalId;
    }

    public String getResultCode() {
        return resultCode;
    }

    public void setResultCode(String resultCode) {
        this.resultCode = resultCode;
    }

    public static class UserInfoBean {
        /**
         * username : 1064611374687
         * password : 123456
         * email : null
         * vin : LVVDC17B2HD186057
         */

        private String username;
        private String password;
        private Object email;
        private String vin;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public Object getEmail() {
            return email;
        }

        public void setEmail(Object email) {
            this.email = email;
        }

        public String getVin() {
            return vin;
        }

        public void setVin(String vin) {
            this.vin = vin;
        }
    }

    public static class VehicleInfoBean {
        /**
         * vin : LVVDC17B2HD186057
         * licenseNum : null
         * vehicleType : M1AEV
         * vehicleStyle : null
         * iccid : 89860616010055022236
         */

        private String vin;
        private Object licenseNum;
        private String vehicleType;
        private Object vehicleStyle;
        private String iccid;

        public String getVin() {
            return vin;
        }

        public void setVin(String vin) {
            this.vin = vin;
        }

        public Object getLicenseNum() {
            return licenseNum;
        }

        public void setLicenseNum(Object licenseNum) {
            this.licenseNum = licenseNum;
        }

        public String getVehicleType() {
            return vehicleType;
        }

        public void setVehicleType(String vehicleType) {
            this.vehicleType = vehicleType;
        }

        public Object getVehicleStyle() {
            return vehicleStyle;
        }

        public void setVehicleStyle(Object vehicleStyle) {
            this.vehicleStyle = vehicleStyle;
        }

        public String getIccid() {
            return iccid;
        }

        public void setIccid(String iccid) {
            this.iccid = iccid;
        }
    }

    public static class VersionInfoBean {
        /**
         * versionFlag :
         * newVersion :
         * versionRemark :
         * versionUrl :
         */

        private String versionFlag;
        private String newVersion;
        private String versionRemark;
        private String versionUrl;

        public String getVersionFlag() {
            return versionFlag;
        }

        public void setVersionFlag(String versionFlag) {
            this.versionFlag = versionFlag;
        }

        public String getNewVersion() {
            return newVersion;
        }

        public void setNewVersion(String newVersion) {
            this.newVersion = newVersion;
        }

        public String getVersionRemark() {
            return versionRemark;
        }

        public void setVersionRemark(String versionRemark) {
            this.versionRemark = versionRemark;
        }

        public String getVersionUrl() {
            return versionUrl;
        }

        public void setVersionUrl(String versionUrl) {
            this.versionUrl = versionUrl;
        }
    }

    public static class ConfigInfoBean {
        /**
         * pollInterval : 600
         * controlPollInterval : 5
         * timeout : 105
         */

        private int pollInterval;
        private int controlPollInterval;
        private int timeout;

        public int getPollInterval() {
            return pollInterval;
        }

        public void setPollInterval(int pollInterval) {
            this.pollInterval = pollInterval;
        }

        public int getControlPollInterval() {
            return controlPollInterval;
        }

        public void setControlPollInterval(int controlPollInterval) {
            this.controlPollInterval = controlPollInterval;
        }

        public int getTimeout() {
            return timeout;
        }

        public void setTimeout(int timeout) {
            this.timeout = timeout;
        }
    }
}

编写网络返回管理类

  • 请求开始progressbar
  • 处理返回成功的数据
  • 遇到错误的情况(404或网络异常)
  • 完成销毁progressbar
package com.weiqun.cherytelematic.network;
import android.accounts.NetworkErrorException;
import com.dejun.commonsdk.base.BaseActivity;
import com.dejun.commonsdk.dialog.ProgressDialogFragment;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
/**
 * @author DcotorWei
 * @date :2019/11/25 11:24
 * @description :TODO
 * @email :[email protected]
 */
public abstract class BaseObserver<T> implements Observer<T> {
    protected BaseActivity mContext;
    private ProgressDialogFragment progressDialogFragment;
    private String labelTxt;

    public BaseObserver(BaseActivity cxt, String text) {
        this.mContext = cxt;
        this.labelTxt = text;
        if (progressDialogFragment == null) {
            progressDialogFragment = ProgressDialogFragment.newInstance(text);
        }
        progressDialogFragment.show(cxt.getSupportFragmentManager(), getClass().getSimpleName());
    }

    public BaseObserver(BaseActivity cxt) {
        this(cxt, "");
    }

    //开始
    @Override
    public void onSubscribe(Disposable d) {
        onRequestStart();
    }

    //成功获取数据
    @Override
    public void onNext(T res) {
        try {
            onSuccees(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取数据失败
    @Override
    public void onError(Throwable e) {
        onRequestEnd();
        try {
            if (e instanceof ConnectException
                    || e instanceof TimeoutException
                    || e instanceof NetworkErrorException
                    || e instanceof UnknownHostException) {
                onFailure(e, true);  //网络错误
            } else {
                onFailure(e, false);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    //结束
    @Override
    public void onComplete() {
        onRequestEnd();//请求结束
    }

    /**
     * 返回成功
     *
     * @param t
     * @throws Exception
     */
    public abstract void onSuccees(T t) throws Exception;


    /**
     * 返回失败
     *
     * @param e
     * @param isNetWorkError 是否是网络错误
     * @throws Exception
     */
    public abstract void onFailure(Throwable e, boolean isNetWorkError) throws Exception;

    public void onRequestStart() {
        if (labelTxt != null && progressDialogFragment != null) {
            progressDialogFragment.setText(labelTxt);
        }
    }

    public void onRequestEnd() {
        if (progressDialogFragment != null) {
            progressDialogFragment.dismiss();
            progressDialogFragment = null;
        }
    }

}

使用

  • 添加子线程的网络请求
  • 切换成主线程
  • 添加返回监听
package com.weiqun.cherytelematic.activity;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.dejun.commonsdk.base.BaseActivity;
import com.gyf.barlibrary.ImmersionBar;
import com.orhanobut.logger.Logger;
import com.weiqun.cherytelematic.CheryApi;
import com.weiqun.cherytelematic.R;
import com.weiqun.cherytelematic.bean.UserBean;
import com.weiqun.cherytelematic.bean.res.LoginRes;
import com.weiqun.cherytelematic.databinding.ActivityLoginBinding;
import com.weiqun.cherytelematic.network.BaseObserver;
import com.weiqun.cherytelematic.network.RetrifitUtil;
import com.weiqun.cherytelematic.service.LoginService;
import java.util.UUID;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    ActivityLoginBinding activityLoginBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this).init();
        activityLoginBinding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        activityLoginBinding.setOnClickListener(this);
        //修改登录界面
        activityLoginBinding.setLoginBean(new UserBean.LoginBean("1064611374687", "123456"));
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_login) {
            UserBean.LoginBean loginBean = new UserBean.LoginBean("DoctorWei", "123456");
            UserBean userBean = new UserBean("ver2.4.114", UUID.randomUUID() + "", "601", "", "a903bbf3-edee-4dad-b5eb-7f86c94c2a39", loginBean);
            RetrifitUtil.getInstance()
                    .getRetrofit(CheryApi.BASE_URL)
                    .create(LoginService.class)
                    //添加请求体
                    .login(userBean)
                    //subscribeOn()主要改变的是订阅的线程,切换到线程池中的子线程,即call()执行的线程,用于网络请求
                    .subscribeOn(Schedulers.io())
                    //observeOn()主要改变的是发送的线程,即onNext()执行的线程,切换成主线程,进行UI的修改
                    .observeOn(AndroidSchedulers.mainThread())
                    //处理回调数据
                    .subscribe(new BaseObserver<LoginRes>(LoginActivity.this,"") {
                        @Override
                        public void onSuccees(LoginRes loginRes) throws Exception {
                            Logger.d(loginRes);
                        }

                        @Override
                        public void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                            if (isNetWorkError){
                                Toast.makeText(LoginActivity.this,"网络异常",Toast.LENGTH_SHORT);
                            }else{
                                Logger.e(e.getMessage());
                            }
                        }
                    });

        }
    }
}

你可能感兴趣的:(Android Retrofit2和Rxjava2的使用)