ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Retrofit2框架封装(源码+java)

2026/9/16 4:15:54 拓冰建站 浏览量
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<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;}@Overridepublic final void onResponse(Call<HttpBaseResult<T>> call, Response<HttpBaseResult<T>> response) {onMyComplete();HttpBaseResult<T> baseBean = response.body();if (baseBean == null) {onMyFailure(HttpBaseResult.STATUS_FAILURE, "Http Body Is NULL");return;}if (baseBean.isSuccess()) {onMySuccess(baseBean.getData());} else {onMyFailure(baseBean.getErrcode(), baseBean.getErrmsg());}}@Overridepublic final void onFailure(Call<HttpBaseResult<T>> call, Throwable t) {onMyComplete();if (t instanceof ConnectException) {onMyFailure(HttpBaseResult.STATUS_NETWORK_UNCONNECTED, "UnConnect Network");} else if (t instanceof SocketTimeoutException) {onMyFailure(HttpBaseResult.STATUS_NETWORK_READTIME_OUT, "ReadTime Out");} else {onMyFailure(HttpBaseResult.STATUS_EXCEPTION, t.getMessage());}}public void onMySuccess(T result) {if (nLiveData != null) {nLiveData.postValue(result);}}public void onMyFailure(int status, String message) {if (isShowFailedToast) {showToast(message);}}public void onMyComplete() {
//            if (mIsShowLoading){hideLoading();
//            }}private void showLoading() {EventBus.getDefault().post(Constant.EVENT_SHOW_LOADING);}private void hideLoading() {EventBus.getDefault().post(Constant.EVENT_HIDE_LOADING);}public void showToast(String message) {ToastUtils.showToast(App.getInstance(), message);}
}

2.3、HttpServiceApi.java

public interface HttpServiceApi {@GET("mintti/remote/getDeviceByDeviceMac")Call<HttpBaseResult<DeviceInfo>> getDeviceMac(@Query("deviceMac") String deviceMac);@POST("mintti/remote/createDevice")Call<HttpBaseResult<DeviceInfo>> createDevice(@Body RequestBody body);
}

2.4、RetrofitHelper.java

public class RetrofitHelper {private static RetrofitHelper retrofitHelper;private static final int READ_TIME_OUT = 10;private static final int CONNECT_TIME_OUT = 10;private final Retrofit mRetrofit;private RetrofitHelper() {OkHttpClient.Builder builder = new OkHttpClient().newBuilder();//设置连接和读取时间builder.readTimeout(READ_TIME_OUT, TimeUnit.SECONDS);builder.connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS);//添加日志拦截器HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);builder.addInterceptor(interceptor);//添加数据请求统一处理拦截器builder.addInterceptor(new Interceptor() {@NonNull@Overridepublic Response intercept(@NonNull Chain chain) throws IOException {Request original = chain.request();Request request = original.newBuilder()
//                    .addHeader("","")//添加请求头.method(original.method(), original.body()).build();return chain.proceed(request);}});OkHttpClient client = builder.build();mRetrofit = new Retrofit.Builder().baseUrl("http://ecg.web.mintti.cn/")//添加自定义的CustomGsonConverterFactory 统一处理返回数据.addConverterFactory(GsonConverterFactory.create()).client(client).build();}public static RetrofitHelper getInstance() {if (retrofitHelper == null) {retrofitHelper = new RetrofitHelper();}return retrofitHelper;}/*** 设置默认的请求接口** @return*/public HttpServiceApi getServiceApi() {return mRetrofit.create(HttpServiceApi.class);}
}

2.5、JsonParams.java

public class JsonParams {JSONObject params = new JSONObject();public JsonParams put(String key, Object value) {try {params.put(key, value);} catch (JSONException e) {e.printStackTrace();}return this;}public RequestBody create() {return RequestBody.create(params.toString(), MediaType.parse("application/json"));}
}

3、请求接口时显示弹窗:

BaseVBindingActivity.java

public abstract class BaseVBindingActivity<VB extends ViewBinding> extends AppCompatActivity {private VB vBinding;private ProgressDialog mProgressDialog;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);vBinding = getViewBinding();setContentView(vBinding.getRoot());EventBus.getDefault().register(this);}protected VB getBinding() {return vBinding;}public abstract VB getViewBinding();private void showLoading() {if (mProgressDialog == null) {mProgressDialog = new ProgressDialog(this);mProgressDialog.setCancelable(true);mProgressDialog.setMessage("加载中...");}mProgressDialog.show();}private void hideLoading() {if (mProgressDialog != null && mProgressDialog.isShowing()) {mProgressDialog.dismiss();}}@Subscribe(threadMode = ThreadMode.MAIN)public void onMessageEvent(String message) {Log.d("caowj", "message=" + message);if (Constant.EVENT_SHOW_LOADING.equals(message)) {showLoading();} else if (Constant.EVENT_HIDE_LOADING.equals(message)) {hideLoading();}}@Overrideprotected void onDestroy() {super.onDestroy();EventBus.getDefault().unregister(this);}
}

4、请求示例:

Get请求:

RetrofitHelper.getInstance().getServiceApi().getDeviceMac(bleAddress).enqueue(new HttpRequestCallback<DeviceInfo>() {@Overridepublic void onMySuccess(DeviceInfo result) {super.onMySuccess(result);if (result != null) {showSerialNumber(result.getDeviceNo());} else {showSerialNumber(null);}}@Overridepublic void onMyFailure(int status, String message) {super.onMyFailure(status, message);showSerialNumber(null);}
});

Post请求:

 RequestBody requestBody = new JsonParams().put("deviceNo", "1111").put("deviceMac", "2222").create();RetrofitHelper.getInstance().getServiceApi().createDevice(requestBody).enqueue(new HttpRequestCallback<DeviceInfo>() {@Overridepublic void onMySuccess(DeviceInfo result) {super.onMySuccess(result);Log.d("caowj", "返回值:" + result);showSerialNumber(code);}});