Retrofit2框架封装(源码+java)

发布时间:2024年01月03日

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<T> {
   
    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<T> implements Callback<HttpBaseResult<T>> {
   

    /**
     * 用于token失效去重
     */
    protected boolean alreadySend = false;
    protected boolean isShowFailedToast = true;//默认显示
    MutableLiveData<T> 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<T> liveData) {
   
        showLoading();
        nLiveData = liveData;
    }

    @Override
    public final void onResponse
文章来源:https://blog.csdn.net/zhijiandedaima/article/details/135366396
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。