搜了好多相關(guān)文章,但是發(fā)現(xiàn)貌似都是基于官方Demo中的例子實(shí)現(xiàn)的。于是照貓畫虎實(shí)現(xiàn)了Java版本。
其實(shí)其中的核心就是自定義CallAdapter來實(shí)現(xiàn)對請求結(jié)果的基礎(chǔ)處理以及轉(zhuǎn)換。
下面開始正文:
正文
- 引入
Retrofit
dependencies {
...
//retrofit
api 'com.squareup.retrofit2:retrofit:2.8.1'
api 'com.squareup.okhttp3:okhttp:4.5.0'
api 'com.squareup.retrofit2:converter-gson:2.5.0'
api 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
}
- 自定義一個請求結(jié)果的泛型
ApiResponse
public class ApiResponse<T> {
public static final int CODE_SUCCESS = 0;
public static final int CODE_ERROR = 1;
public int code; //狀態(tài)碼
public String msg; //信息
public T data; //數(shù)據(jù)
public ApiResponse(int code, String msg) {
this.code = code;
this.msg = msg;
this.data = null;
}
public ApiResponse(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
}
- 自定義
LiveDataCallAdapter
public class LiveDataCallAdapter<T> implements CallAdapter<T, LiveData<T>> {
private Type mResponseType;
private boolean isApiResponse;
LiveDataCallAdapter(Type mResponseType, boolean isApiResponse) {
this.mResponseType = mResponseType;
this.isApiResponse = isApiResponse;
}
@NotNull
@Override
public Type responseType() {
return mResponseType;
}
@NotNull
@Override
public LiveData<T> adapt(@NotNull final Call<T> call) {
return new MyLiveData<>(call, isApiResponse);
}
private static class MyLiveData<T> extends LiveData<T> {
private AtomicBoolean stared = new AtomicBoolean(false);
private final Call<T> call;
private boolean isApiResponse;
MyLiveData(Call<T> call, boolean isApiResponse) {
this.call = call;
this.isApiResponse = isApiResponse;
}
@Override
protected void onActive() {
super.onActive();
//確保執(zhí)行一次
if (stared.compareAndSet(false, true)) {
call.enqueue(new Callback<T>() {
@Override
public void onResponse(@NotNull Call<T> call, @NotNull Response<T> response) {
T body = response.body();
postValue(body);
}
@Override
public void onFailure(@NotNull Call<T> call, @NotNull Throwable t) {
if (isApiResponse) {
//noinspection unchecked
postValue((T) new ApiResponse<>(ApiResponse.CODE_ERROR, t.getMessage()));
} else {
postValue(null);
}
}
});
}
}
}
}
- 自定義
LiveDataCallAdapterFactory
public class LiveDataCallAdapterFactory extends CallAdapter.Factory {
private static final String TAG = LiveDataCallAdapterFactory.class.getSimpleName();
@SuppressWarnings("ClassGetClass")
@Nullable
@Override
public CallAdapter<?, ?> get(@NotNull Type returnType, @NotNull Annotation[] annotations, @NotNull Retrofit retrofit) {
if (getRawType(returnType) != LiveData.class) {
return null;
}
//獲取第一個泛型類型
Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
Class<?> rawType = getRawType(observableType);
Log.d(TAG, "rawType = " + rawType.getClass().getSimpleName());
boolean isApiResponse = true;
if (rawType != ApiResponse.class) {
//不是返回ApiResponse類型的返回值
isApiResponse = false;
}
if (observableType instanceof ParameterizedType) {
throw new IllegalArgumentException("resource must be parameterized");
}
return new LiveDataCallAdapter<>(observableType, isApiResponse);
}
}
兩個核心類就完成了。
- 自定義
Retrofit管理類RetrofitManager
public class RetrofitManager {
//服務(wù)器請求baseUrl
private static String sBaseUrl = null;
//超時時長 默認(rèn)10s
private static int sConnectTimeout = 10;
//用于存儲retrofit
private static ConcurrentHashMap<String, Retrofit> sRetrofitMap;
private static OkHttpClient.Builder sOkHttpBuilder;
//用于日期轉(zhuǎn)換
private static Gson sDataFormat;
static {
sRetrofitMap = new ConcurrentHashMap<>();
sOkHttpBuilder = new OkHttpClient.Builder();
//超時時長
sOkHttpBuilder.connectTimeout(sConnectTimeout, TimeUnit.SECONDS);
sDataFormat = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
.create();
}
//初始化主要的baseUrl 便于后期直接獲取
public static void init(String baseUrl) {
sBaseUrl = baseUrl;
}
public static String getsBaseUrl() {
return sBaseUrl;
}
public static void setConnectTimeout(int connectTimeout) {
sConnectTimeout = connectTimeout;
}
public static Retrofit get() {
Retrofit retrofit = sRetrofitMap.get(sBaseUrl);
if (retrofit == null) {
throw new RuntimeException("BASE_URL為空");
}
return retrofit;
}
public static Retrofit get(String baseUrl) {
Retrofit retrofit = sRetrofitMap.get(baseUrl);
if (retrofit == null) {
retrofit = createRetrofit(baseUrl);
sRetrofitMap.put(baseUrl, retrofit);
}
return retrofit;
}
/**
* 創(chuàng)建Retrofit對象
*
* @param baseUrl baseUrl
* @return Retrofit
*/
private static Retrofit createRetrofit(String baseUrl) {
return new Retrofit.Builder()
.baseUrl(baseUrl)
.client(sOkHttpBuilder.build())
.addCallAdapterFactory(new LiveDataCallAdapterFactory())
.addConverterFactory(GsonConverterFactory.create(sDataFormat))
.build();
}
}
- 最后再定義一個結(jié)果類和
Service,這里以請求Bing的每日一圖為例
public class BingImg {
//bing每日一圖:https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1
public static final String REQUEST_URL = "https://cn.bing.com/";
private static final String BASE_IMAGE_URL = "https://www.bing.com/";
/**
* images : [{"startdate":"20200413","fullstartdate":"202004131600","enddate":"20200414","url":"/th?id=OHR.BWFlipper_ZH-CN1813139386_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp","urlbase":"/th?id=OHR.BWFlipper_ZH-CN1813139386","copyright":"伊斯塔帕海岸的熱帶斑海豚,墨西哥 (? Christian Vizl/Tandem Stills + Motion)","copyrightlink":"https://www.bing.com/search?q=%E7%83%AD%E5%B8%A6%E6%96%91%E6%B5%B7%E8%B1%9A&form=hpcapt&mkt=zh-cn","title":"","quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20200413_BWFlipper%22&FORM=HPQUIZ","wp":true,"hsh":"b8381f6da75ae67b3581c0ca162718ac","drk":1,"top":1,"bot":1,"hs":[]}]
* tooltips : {"loading":"正在加載...","previous":"上一個圖像","next":"下一個圖像","walle":"此圖片不能下載用作壁紙。","walls":"下載今日美圖。僅限用作桌面壁紙。"}
*/
public TooltipsBean tooltips;
public List<ImagesBean> images;
public static class TooltipsBean {
/**
* loading : 正在加載...
* previous : 上一個圖像
* next : 下一個圖像
* walle : 此圖片不能下載用作壁紙。
* walls : 下載今日美圖。僅限用作桌面壁紙。
*/
public String loading;
public String previous;
public String next;
public String walle;
public String walls;
}
public static class ImagesBean {
/**
* startdate : 20200413
* fullstartdate : 202004131600
* enddate : 20200414
* url : /th?id=OHR.BWFlipper_ZH-CN1813139386_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
* urlbase : /th?id=OHR.BWFlipper_ZH-CN1813139386
* copyright : 伊斯塔帕海岸的熱帶斑海豚,墨西哥 (? Christian Vizl/Tandem Stills + Motion)
* copyrightlink : https://www.bing.com/search?q=%E7%83%AD%E5%B8%A6%E6%96%91%E6%B5%B7%E8%B1%9A&form=hpcapt&mkt=zh-cn
* title :
* quiz : /search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20200413_BWFlipper%22&FORM=HPQUIZ
* wp : true
* hsh : b8381f6da75ae67b3581c0ca162718ac
* drk : 1
* top : 1
* bot : 1
* hs : []
*/
public String startdate;
public String fullstartdate;
public String enddate;
public String url;
public String urlbase;
public String copyright;
public String copyrightlink;
public String title;
public String quiz;
public boolean wp;
public String hsh;
public int drk;
public int top;
public int bot;
public List<?> hs;
}
/**
* 獲取每日一圖的url
*
* @return url
*/
public String getImgUrl() {
if (images != null && images.size() >= 1) {
return BASE_IMAGE_URL + images.get(0).url;
}
return null;
}
}
public interface SplashService {
@GET("HPImageArchive.aspx?format=js&idx=0&n=1")
Call<BingImg> getBingImg();
@GET("HPImageArchive.aspx?format=js&idx=0&n=1")
LiveData<BingImg> getBingImgLiveData();
}
使用
RetrofitManager.get("https://cn.bing.com/")
.create(SplashService.class)
.getBingImgLiveData().observe(this, new Observer<BingImg>() {
@Override
public void onChanged(BingImg bingImg) {
Log.d(TAG, "onChanged: 請求結(jié)果:"+new Gson().toJson(bingImg));
}
});