RxJava和Retrofit2的統(tǒng)一處理單個(gè)請(qǐng)求示例詳解
前言
RxJava和Retrofit2用了一段時(shí)間了,寫個(gè)小例子,分享出來(lái),有什么不對(duì)的地方還請(qǐng)大神在評(píng)論區(qū)指正。
什么是Retrofit2
官網(wǎng)是這么介紹的:
Retrofit adapts a Java interface to HTTP calls by using annotations on the declared methods to
define how requests are made。
我翻譯的可能不準(zhǔn)確,他的大概意思是說(shuō):Retrofit 是一個(gè) java 接口類,以注解的方式用于 HTTP 網(wǎng)絡(luò)請(qǐng)求。那下面我們一起來(lái)看看是怎么使用的?
發(fā)現(xiàn)問(wèn)題
最近在幫兄弟公司做一個(gè)資訊類的項(xiàng)目,使用了RxJava和Retrofit2這對(duì)黃金組合,在編寫代碼的過(guò)程中發(fā)現(xiàn)有很多很多的網(wǎng)絡(luò)請(qǐng)求都需要做.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).onErrorReturn()的處理,為避免這樣,需要沉思。
解決問(wèn)題
import android.util.Log;
import com.wei.caiqiwang.data.entity.BaseResponse;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class RxNet {
/**
* 統(tǒng)一處理單個(gè)請(qǐng)求
*/
public static <T> Subscription request(Observable<BaseResponse<T>> observable, final RxNetCallBack<T> callBack) {
return observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorReturn(new Func1<Throwable, BaseResponse<T>>() {
@Override
public BaseResponse<T> call(Throwable throwable) {
Log.v("LinNetError",throwable.getMessage());
callBack.onFailure(ExceptionHandle.handleException(throwable));
return null;
}
})
.subscribe(new Subscriber<BaseResponse<T>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(BaseResponse<T> baseResponse) {
if (baseResponse.getCode().equals("200")) {
callBack.onSuccess(baseResponse.getData());
} else {
callBack.onFailure(baseResponse.getMsg());
}
}
});
}
/**
* 統(tǒng)一處理單個(gè)請(qǐng)求沒(méi)有 msg body
*/
public static Subscription requestWithoutBody(Observable<BaseResponse> observable, final RxNetCallBack<String> callBack) {
return observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorReturn(new Func1<Throwable, BaseResponse>() {
@Override
public BaseResponse call(Throwable throwable) {
callBack.onFailure(ExceptionHandle.handleException(throwable));
return null;
}
})
.subscribe(new Subscriber<BaseResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(BaseResponse baseResponse) {
if (baseResponse.getCode().equals("200")) {
callBack.onSuccess(baseResponse.getMsg());
} else {
callBack.onFailure(baseResponse.getMsg());
}
}
});
}
}
回調(diào)就是普通的回調(diào)
public interface RxNetCallBack<T> {
/**
* 數(shù)據(jù)請(qǐng)求成功
*
* @param data 請(qǐng)求到的數(shù)據(jù)
*/
void onSuccess(T data);
/**
* 數(shù)據(jù)請(qǐng)求失敗
*/
void onFailure(String msg);
}
錯(cuò)誤異常處理(可能不全):
import android.net.ParseException;
import com.google.gson.JsonParseException;
import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import java.net.ConnectException;
import retrofit2.HttpException;
public class ExceptionHandle {
private static final int UNAUTHORIZED = 401;
private static final int FORBIDDEN = 403;
private static final int NOT_FOUND = 404;
private static final int REQUEST_TIMEOUT = 408;
private static final int INTERNAL_SERVER_ERROR = 500;
private static final int BAD_GATEWAY = 502;
private static final int SERVICE_UNAVAILABLE = 503;
private static final int GATEWAY_TIMEOUT = 504;
public static String handleException(Throwable e) {
String errorMsg;
if (e instanceof HttpException) {
HttpException httpException = (HttpException) e;
switch (httpException.code()) {
case UNAUTHORIZED:
case FORBIDDEN:
case NOT_FOUND:
case REQUEST_TIMEOUT:
case GATEWAY_TIMEOUT:
case INTERNAL_SERVER_ERROR:
case BAD_GATEWAY:
case SERVICE_UNAVAILABLE:
default:
errorMsg = "網(wǎng)絡(luò)錯(cuò)誤";
break;
}
return errorMsg + ":" + httpException.code();
} else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {
return "解析錯(cuò)誤";
} else if (e instanceof ConnectException) {
return "連接失敗";
} else if (e instanceof javax.net.ssl.SSLHandshakeException) {
return "證書驗(yàn)證失敗";
} else if (e instanceof ConnectTimeoutException) {
return "連接超時(shí)";
} else if (e instanceof java.net.SocketTimeoutException) {
return "連接超時(shí)";
} else {
return "未知錯(cuò)誤";
}
}
}
然后就是ApiManager:
import android.util.Log;
import com.wei.demo.data.AppConstants;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiManager {
private Retrofit client;
private ApiManager() {
client = new Retrofit.Builder()
.baseUrl(AppConstants.Base_Url_Api_Test)
.client(initClient())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
private static volatile DemoApi INSTANCE;
public static DemoApi getInstance() {
if (INSTANCE == null) {
synchronized (ApiManager.class) {
if (INSTANCE == null) {
INSTANCE = new ApiManager().getApi();
}
}
}
return INSTANCE;
}
private DemoApi getApi() {
return client.create(DemoApi.class);
}
private static OkHttpClient initClient() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//聲明日志類
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.v("NetLog", message);
}
});
//設(shè)定日志級(jí)別
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//延時(shí)
builder.addInterceptor(httpLoggingInterceptor)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS);
return builder.build();
}
}
怎么用?
RxNet.request(ApiManager.getInstance().getUserMsg(map), new RxNetCallBack<List<MsgBean>>() {
@Override
public void onSuccess(List<MsgBean> data) {
// 處理數(shù)據(jù)
}
@Override
public void onFailure(String msg) {
//出現(xiàn)了錯(cuò)誤
showToast(msg);
}
});
Demo https://github.com/FriendLin/NetRequestDemo (本地下載)
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
- Android中的Retrofit+OkHttp+RxJava緩存架構(gòu)使用
- RxJava2.x+ReTrofit2.x多線程下載文件的示例代碼
- Retrofit Rxjava實(shí)現(xiàn)圖片下載、保存并展示實(shí)例
- 詳解RxJava2 Retrofit2 網(wǎng)絡(luò)框架簡(jiǎn)潔輕便封裝
- RxJava+Retrofit+OkHttp實(shí)現(xiàn)多文件下載之?dāng)帱c(diǎn)續(xù)傳
- Retrofit+Rxjava實(shí)現(xiàn)文件上傳和下載功能
- Kotlin結(jié)合Rxjava+Retrofit實(shí)現(xiàn)極簡(jiǎn)網(wǎng)絡(luò)請(qǐng)求的方法
- RxJava+Retrofit+OkHttp實(shí)現(xiàn)文件上傳
- Retrofit+Rxjava下載文件進(jìn)度的實(shí)現(xiàn)
- rxjava+retrofit實(shí)現(xiàn)多圖上傳實(shí)例代碼
相關(guān)文章
36個(gè)Android開(kāi)發(fā)常用經(jīng)典代碼大全
本篇文章主要介紹了36個(gè)Android開(kāi)發(fā)常用經(jīng)典代碼片段,都是實(shí)用的代碼段,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2016-11-11
Android手冊(cè)之Toolbar搜索聯(lián)動(dòng)及監(jiān)聽(tīng)小技巧
這篇文章主要為大家介紹了Android手冊(cè)之Toolbar搜索聯(lián)動(dòng)及監(jiān)聽(tīng)小技巧示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
android @override 報(bào)錯(cuò)解決方案
android @override 報(bào)錯(cuò):就是說(shuō)Java 1.5的編譯器默認(rèn)對(duì)父類的方法進(jìn)行覆蓋,采用@Override進(jìn)行說(shuō)明;但1.6已經(jīng)擴(kuò)展到對(duì)接口的方法;所以如果還是以Java 1.5的編譯器來(lái)編譯的話,會(huì)出現(xiàn)錯(cuò)誤2012-12-12
Android中AsyncTask的入門使用學(xué)習(xí)指南
AsyncTask異步任務(wù),用于執(zhí)行耗時(shí)任務(wù)并在UI線程中更新結(jié)果。下面這篇文章主要給大家介紹了關(guān)于Android中AsyncTask入門使用的相關(guān)資料,需要的朋友可以參考下2019-02-02
Android 設(shè)置應(yīng)用全屏的兩種解決方法
本篇文章小編為大家介紹,Android 設(shè)置應(yīng)用全屏的兩種解決方法。需要的朋友參考下2013-04-04
Android組合式自定義控件實(shí)現(xiàn)購(gòu)物車加減商品操作
這篇文章主要介紹了Android組合式自定義控件實(shí)現(xiàn)購(gòu)物車加減商品操作,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11
Android中使用HttpURLConnection實(shí)現(xiàn)GET POST JSON數(shù)據(jù)與下載圖片
這篇文章主要介紹了Android中使用HttpURLConnection實(shí)現(xiàn)GET POST JSON數(shù)據(jù)與下載圖片,需要的朋友可以參考下2016-01-01
Android利用廣播接收器實(shí)現(xiàn)自動(dòng)填充短信驗(yàn)證碼
這篇文章主要為大家詳細(xì)介紹了Android利用廣播接收器實(shí)現(xiàn)自動(dòng)填充短信驗(yàn)證碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12

