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

    @Override
    public 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());
        }
    }

    @Override
    public 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
            @Override
            public 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;

    @Override
    protected 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();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

4、请求示例:

Get请求:

RetrofitHelper.getInstance().getServiceApi().getDeviceMac(bleAddress).enqueue(new HttpRequestCallback<DeviceInfo>() {
    @Override
    public void onMySuccess(DeviceInfo result) {
        super.onMySuccess(result);
        if (result != null) {
            showSerialNumber(result.getDeviceNo());
        } else {
            showSerialNumber(null);
        }
    }

    @Override
    public 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>() {
     @Override
     public void onMySuccess(DeviceInfo result) {
         super.onMySuccess(result);
         Log.d("caowj", "返回值:" + result);
         showSerialNumber(code);
     }
 });
  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OkHttp3和Retrofit2是两个在Java开发中常用的网络请求库,它们可以帮助我们方便地进行网络请求和数据解析。 OkHttp3是一个高效、可靠的HTTP客户端,它支持HTTP/2协议,可以处理网络请求、连接池、缓存等功能。它提供了简洁的API,使得发送HTTP请求变得非常简单。你可以使用OkHttp3来发送GET、POST等各种类型的请求,并且可以设置请求头、请求参数、超时时间等。 Retrofit2是一个基于OkHttp3的RESTful风格的网络请求库,它可以将HTTP API转换为Java接口。通过定义接口的方式,我们可以使用注解来描述请求的URL、请求方法、请求参数等信息。Retrofit2会根据这些注解自动生成相应的网络请求代码,使得我们可以以更加简洁的方式进行网络请求。 使用OkHttp3和Retrofit2进行网络请求的步骤如下: 1. 添加依赖:在项目的build.gradle文件中添加OkHttp3和Retrofit2的依赖。 2. 创建OkHttpClient对象:可以设置一些通用的配置,比如连接超时时间、读写超时时间等。 3. 创建Retrofit对象:通过Retrofit.Builder来创建Retrofit对象,并设置baseUrl、OkHttpClient等。 4. 定义接口:创建一个Java接口,使用注解描述请求的URL、请求方法、请求参数等信息。 5. 创建接口实例:通过Retrofit.create()方法来创建接口的实例。 6. 发起网络请求:调用接口实例的方法来发起网络请求,并处理响应结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值