本文基于java集成retorfit的统一返回类型
第一步构建RetrofitMananger
package com.example.commonui;
import android.content.Context;
import com.example.commonui.adapter.CommonCallAdapter;
import java.io.File;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.hilt.android.qualifiers.ApplicationContext;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
@Singleton
public class RetrofitMananger {
private long DEFAULT_TIME_OUT = 30;
private Context context;
private Retrofit retrofit;
private String base_url = "https://mock.presstime.cn/";
@Inject
public RetrofitMananger(@ApplicationContext Context context) {
this.context = context;
init();
}
private void init() {
retrofit = new Retrofit.Builder()
.client(getOkHttpClientBuilder().build())
.addCallAdapterFactory(new CommonCallAdapter.Factory())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(base_url)
.build();
}
private OkHttpClient.Builder getOkHttpClientBuilder() {
File cacheFile = new File(context.getCacheDir(), "cache");
Cache cache = new Cache(cacheFile, 1024 * 1024 * 100);//100Mb
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
.writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
.readTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.cache(cache)
.addInterceptor(chain -> {
Request request = chain.request();
Request newResult = request.newBuilder()
.addHeader("Accept-Encoding", "gzip")
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json; charset=utf-8")
.method(request.method(), request.body())
.addHeader("Authorization", "Bearer ").build();
return chain.proceed(newResult);
});
return builder;
}
public <T> T create(Class<T> clas){
return retrofit.create(clas);
}
}
第二部构建CommonCallAdapter
package com.example.commonui.adapter;
import androidx.annotation.Nullable;
import com.example.commonui.model.CustomCall;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Response;
import retrofit2.Retrofit;
public class CommonCallAdapter<R> implements CallAdapter<R, CustomCall<R>> {
private Type type;
public CommonCallAdapter(Type type) {
this.type = type;
}
@Override
public Type responseType() {
return type;
}
@Override
public CustomCall<R> adapt(Call<R> call) {
CustomCall<R> result = CustomCall.unknownError();
try {
Response<R> response = null;
if (call.isCanceled()) {
result = CustomCall.cancelError();
} else if ((response = call.execute()).isSuccessful()) {
result = CustomCall.success(response.code(), response.message(), response.body());
} else {
result = CustomCall.error(response.code(), response.message());
}
} catch (Exception e) {
e.printStackTrace();
result.setMessage(e.getMessage());
}
ResultHandler.handlerResult(result);
return result;
}
public static class Factory extends CallAdapter.Factory {
@Nullable
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
//获取原始类型
Class<?> rawType = getRawType(returnType);
if (rawType == CustomCall.class && returnType instanceof ParameterizedType) {
Type callReturnType = getParameterUpperBound(0, (ParameterizedType) returnType);
return new CommonCallAdapter<>(callReturnType);
}
return null;
}
}
}
CustomCall代码如下
package com.example.commonui.model;
public class CustomCall<T> {
private int code;
private boolean success;
private String message;
private T data;
public static CustomCall cancelError(){
return error(-1,"请求被取消");
}
public static CustomCall unknownError(){
return error(-2,"未知错误");
}
public static CustomCall error(int code, String message){
CustomCall<String> customResultInfo = new CustomCall<>();
customResultInfo.message = message;
customResultInfo.code = code;
return customResultInfo;
}
public static <T> CustomCall success(int code, String message, T data){
CustomCall<T> customResultInfo = new CustomCall<>();
customResultInfo.message = message;
customResultInfo.code = code;
customResultInfo.success = true;
customResultInfo.data = data;
return customResultInfo;
}
public int getCode() {
return code;
}
public boolean isSuccess() {
return success;
}
public String getMessage() {
return message;
}
public void setCode(int code) {
this.code = code;
}
public void setSuccess(boolean success) {
this.success = success;
}
public void setMessage(String message) {
this.message = message;
}
public void setData(T data) {
this.data = data;
}
public T getData() {
return data;
}
}
ResultHandler代码如下
package com.example.commonui.adapter;
import com.example.commonui.model.CustomCall;
import com.example.commonui.model.Result;
public class ResultHandler {
public static void handlerResult(CustomCall customCall){
if(customCall.isSuccess()){
if(customCall.getData() instanceof Result){
Result result = (Result)customCall.getData();
if(result.getData() == null){
result.setCode(-3);
result.setMessage("返回的json不匹配");
}
}
}else{
Result<String> result = new Result<>();
result.setCode(customCall.getCode());
result.setMessage(customCall.getMessage());
customCall.setData(result);
}
}
}
Result代码如下
package com.example.commonui.model;
public class Result<T> {
private int code;
private boolean success;
private String message;
private T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
UserManager代码如下
package com.example.myapplication.service;
import com.example.commonui.api.UserServiceApi;
import com.example.commonui.hiltModule.User;
import com.example.commonui.model.Result;
import javax.inject.Inject;
public class UserManager {
private UserServiceApi userServiceApi;
@Inject
public UserManager(UserServiceApi userServiceApi){
this.userServiceApi = userServiceApi;
}
public Result<User> getUser(){
return userServiceApi.getUser().getData();
}
}
接口定义如下:
package com.example.commonui.api;
import com.example.commonui.hiltModule.User;
import com.example.commonui.model.CustomCall;
import com.example.commonui.model.Result;
import retrofit2.http.GET;
public interface UserServiceApi {
@GET("mock/61ef6708f5af18001654fe74/example/query")
CustomCall<Result<User>> getUser();
}
网友评论