Retrofit2框架封装(源码+java)

1、引入依赖库:

    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0'
//    implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
//    implementation 'com.blankj:utilcode:1.30.1'
    implementation 'org.greenrobot:eventbus:3.3.1'

2、网络请求模块:

2.1、HttpBaseResult.java

public class HttpBaseResult {
   
    public static int STATUS_EXCEPTION = -1;
    public static int STATUS_FAILURE = -2;
    public static int STATUS_NETWORK_UNCONNECTED = -10;
    public static int STATUS_NETWORK_READTIME_OUT = -11;
    public static int STATUS_OK = 200;

    private int errcode;
    private String errmsg;
    private T data;
//    private int status;
//    private long timeElapsed;
//    private long timestamp;


    public int getErrcode() {
   
        return errcode;
    }

    public void setErrcode(int errcode) {
   
        this.errcode = errcode;
    }

    public String getErrmsg() {
   
        return errmsg;
    }

    public void setErrmsg(String errmsg) {
   
        this.errmsg = errmsg;
    }

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

    public boolean isSuccess() {
   
        return (errcode == STATUS_OK || errcode == 0) || (String.valueOf(STATUS_OK).equals(errcode));
    }
}

2.2、HttpRequestCallback.java


public class HttpRequestCallback implements Callback> {
   

    /**
     * 用于token失效去重
     */
    protected boolean alreadySend = false;
    protected boolean isShowFailedToast = true;//默认显示
    MutableLiveData nLiveData;
    private boolean mIsShowLoading = true;


    public HttpRequestCallback() {
   
        showLoading();
    }

    public HttpRequestCallback(boolean isShowLoading) {
   
        mIsShowLoading = isShowLoading;
        if (isShowLoading) {
   
            showLoading();
        }
    }

    public HttpRequestCallback(boolean isShowLoading, boolean isShowToast) {
   
        this.isShowFailedToast = isShowToast;
        if (isShowLoading) {
   
            showLoading();
        }
    }


    public HttpRequestCallback(MutableLiveData liveData) {
   
        showLoading();
        nLiveData = liveData;
    }

    @Override
    public final void onResponse

你可能感兴趣的:(Retrofit2,java,retrofit,网络请求框架,Retrofit2封装)