1. 说明
Retrofit+RxJava这套组合的网络框架在Android开发中还是相对好用的,本文根据自身实验简要说明一下其用法。若有大佬路过,发现其中不妥,还请指出。
2. 用法
Step1: 建立后台返回的JSON数据
private Integer status; //状态码
private String message; //返回信息
private Object obj; //返回对象
Step2: 前端接受的基本数据类型
private int status;
private String message;
private T obj;
这里需要注意: (1)前后端的对应参数名一定要对应,例如:status 对应 status. 因为前端是通过GSON去进行解析,如果参数名不对应,最后解析不了。 (2)后端的obj如果传输的是Bean实体类,那用前端用来的接受的Bean的实体类里面的参数名一定要和后端的实体类的参数一一对应。
Step3:android端导入依赖(后面步骤都是在android端了)
(1)引入RxJava和Retrofit依赖
// Rxjava
implementation "io.reactivex.rxjava2:rxjava:2.2.6" // 必要rxjava依赖
implementation "io.reactivex.rxjava2:rxandroid:2.1.0" // 必要rxandrroid依赖,切线程时需要用到
// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.8.1' // 必要retrofit依赖
implementation 'com.squareup.retrofit2:converter-gson:2.8.1' // 必要依赖,解析json字符所用
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0' //非必要依赖,log依赖,如果需要打印OkHttpLog需要添加
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0' // 必要依赖,和rxjava结合必须用到
(2)在AndroidManifest.xml中加入网络权限
<uses-permission android:name="android.permission.INTERNET"/>
Step4:先写统一的异常处理类
public class ServerException extends Exception {
private int code;
public ServerException(String message){
super(message);
}
public ServerException(int code, String mes){
super(mes);
this.code=code;
}
public int getCode(){
return code;
}
@Override
public String toString(){
return "ServerException{"+
"code="+code+
'}';
}
}
Step5: RxJava对网络返回请求的统一处理
//RxJava对网络请求的统一处理
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
public class RxHelper {
//去壳处理
public static <T>ObservableTransformer<BaseResponse<T>,T> handleResult(){
return new ObservableTransformer<BaseResponse<T>, T>() {
@Override
public ObservableSource<T> apply(Observable<BaseResponse<T>> upstream) {
return (ObservableSource<T>) upstream.flatMap(new Function<BaseResponse<T>, ObservableSource<?>>() {
@Override
public ObservableSource<?> apply(BaseResponse<T> tBaseResponse) throws Exception {
int code=tBaseResponse.getStatus();
String desc=tBaseResponse.getMessage();
T data=tBaseResponse.getObj();
//Log.e("CTB_RxHelper: ", data.toString());
if(code==ServiceFactory.NET_SUCCESS_CODE){
return createObservable(data);
}else{
return Observable.error(new ServerException(code,desc));
}
}
}).subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
// 创建指定数据源的Observable
// 即:将后端传来的数据,如果为空,则则直接走 onComplete(); 否则,走onNext(),即传数据
private static <T> Observable<T> createObservable(final T t) {
return Observable.create(new ObservableOnSubscribe<T>() {
@Override
public void subscribe(ObservableEmitter<T> e) {
if (e != null) {
if (t != null) {
e.onNext(t); // 到observe的onNext()
}
e.onComplete();
}
}
});
}
}
Step6: OKHttpClientFactory类
//okHttp设置
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
@SuppressWarnings("deprecation")
public class OKHttpClientFactory {
private static OkHttpClient defaultClient;
public static OkHttpClient getDefaultOkClient() {
SSLSocketFactory socketFactory=null;
if(defaultClient==null){
synchronized (OKHttpClientFactory.class){
if(defaultClient==null){
final TrustManager[] trustAllCerts=new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
};
try{
SSLContext sslContext=SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
socketFactory = sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BOBY);
defaultClient = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
// .addInterceptor(new UnifiedRequestHead())
.addInterceptor(httpLoggingInterceptor)
.sslSocketFactory(socketFactory)
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
})
.build();
}
}
}
return defaultClient;
}
}
Step7: SeviceFactory
import android.content.Context;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceFactory {
private static String BASE_URL="http://192.168.137.1:8081/"; //ip地址
public static int NET_SUCCESS_CODE=200; // 请求成功返回的code
private static ServiceFactory serviceFactory;
private ApiService apiService; //登录模块
//单例模式
public static ServiceFactory getServiceFactory(){
if(serviceFactory==null){
synchronized (ServiceFactory.class){
if(serviceFactory==null){
serviceFactory=new ServiceFactory();
}
}
}
return serviceFactory;
}
public ApiService getApiService(Context context){
if(apiService==null){
synchronized (ServiceFactory.class){
if(apiService==null){
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(OKHttpClientFactory.getDefaultOkClient())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
apiService=retrofit.create(ApiService.class);
}
}
}
return apiService;
}
}
Step8: BaseModel
public class BaseModel {
public Observable<Buyer> buyerRegister(Context context, Buyer buyer){
return ServiceFactory.getServiceFactory()
.getApiService(context)
.buyerRegister(buyer)
.compose(RxHelper.<Buyer>handleResult());
}
}
Step9: ApiService
public interface ApiService {
@POST("buyer/register")
Observable<BaseResponse<Buyer>> buyerRegister(@Body Buyer buyer);
Step10:在activity或其他地方调用
@SuppressLint("CheckResult")
private void buyerRegister(Context context, String url, Buyer buyer){
new BaseModel().buyerRegister(context, buyer)
.subscribe(new Observer<Buyer>() {
@Override
public void onSubscribe(Disposable d) {
Toast.makeText(context, "onSub: "+d.toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(Buyer buyer) {
// 对返回数据进行处理
Toast.makeText(context, "OnNext: "+buyer.toString(), Toast.LENGTH_SHORT).show();
Log.d("CTB_register:", buyer.toString());
}
@Override
public void onError(Throwable e) {
// 出现错误
Toast.makeText(context, "error: "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onComplete() {
// 注册成功
Toast.makeText(context, "注册成功: ", Toast.LENGTH_SHORT).show();
}
});
}
|