Retrofit2 的使用与封装
响应基类
public class BaseResponse {
public String code;
public String message;
}
请求数据对象基类
public class BaseRequest {
public String productGuid = BuildConfig.PRODUCT_GUID;
public int version = 1;
public int clientType = 1;
}
BaseNetClient
public class BaseNetClient {
...
private BaseNetClient() {
Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(BuildConfig.HOST)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
if (BuildConfig.LOG_DEBUG) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(Config.LOG_MODE);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.connectTimeout(5, TimeUnit.SECONDS)
.build();
builder.client(client);
}
retrofit = builder.build();
}
public <T> T createService(Class<T> service) {
return retrofit.create(service);
}
}
BaseNetHelper
public abstract class BaseNetHelper<T> implements BaseINetHelper {
protected T service;
private Call call;
protected BaseNetHelper(Class<T> service) {
if (service != null && this.service == null) {
this.service = BaseNetClient.getInstance()
.createService(service);
}
}
protected <E extends BaseResponse> void initCall(Call<E> call, BaseCallBack<E> callBack) {
initCall(false, call, callBack);
}
protected <E extends BaseResponse> void initCall(boolean cancelCallBefore, Call<E> call, BaseCallBack<E> callBack) {
if (cancelCallBefore) cancelCall();
call.enqueue(callBack);
this.call = call;
}
@Override
public void cancelCall() {
if (call != null) {
call.cancel();
call = null;
}
}
}
BaseCallBack
public abstract class BaseCallBack<T extends BaseResponse> implements Callback<T> {
@Override
public void onResponse(Call<T> call, Response<T> response) {
try {
if (response.body() != null) {
String code = response.body().code;
if (code.startsWith("2")) {
onSuccess(code, response.body());
} else if (code.startsWith("3")) {
onFailure(code, response.body().message);
} else if (code.startsWith("4")) {
CrashReport.postCatchedException(new Throwable(response.body().code + ":" + response.body().message));
onFailure(code, "请求异常 + 异常码: " + code);
} else {
onFailure("999", "未知异常");
}
}else {
onFailure(ERROR_DATABASE_ERROR, response.errorBody().toString());
}
}catch (Exception e){
onFailure("999", "数据错误");
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
}
protected abstract void onSuccess(String code, T result);
protected abstract void onFailure(String code, String message);
}