此文章随手记录,喜欢的拿走不谢,不喜欢的勿喷,希望提宝贵意见;
1.多组件情况下,肯定少不了一个moduleBase组件,存放一些所有人都可以使用的功能,就好比网络请求模块,当然也可以写一个httpModule脱离moduleBase也许结构更清晰,怎么写可以由自己去决定,此文章不做过多的讨论;
在你的module(httpModule或者moduleBase)build.gradle里增加依赖:
//retrofit网络请求框架
api'com.squareup.retrofit2:retrofit:2.5.0'
//retrofit添加Json解析返回数据
api'com.squareup.retrofit2:converter-gson:2.5.0'
//retrofit添加Rxjava支持
api'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
//rxjava框架
api'com.trello.rxlifecycle2:rxlifecycle-components:2.1.0'
2.在module里新建两个包,分别为base和htpps,
3.在base下创建两个类分别为BaseApi、BaseResponse:
BaseApi.class如下:
public class BaseApi {
public static String getBaseUrl() {
//全局的baseUrl
return "http://120.78.186.81/api/";
}
}
BaseResponse.class如下,主要是针对服务器响应数据封装:
一般情况都是一个code一个msg和泛型T也就是你想要的数据;
public class BaseResponse<T> {
private int res_code;
private Stringerr_msg;
private T demo;
public int getRes_code() {
return res_code;
}
public void setRes_code(int res_code) {
this.res_code = res_code;
}
public String getErr_msg() {
return err_msg;
}
public void setErr_msg(String err_msg) {
this.err_msg = err_msg;
}
public T getDemo() {
return demo;
}
public void setDemo(T demo) {
this.demo = demo;
}
4.https包下的代码如下:
RxExceptionUtil.class 异常统一处理封装类:
/**
* 异常处理
*/
public class RxExceptionUtil {
public static String exceptionHandler(Throwable e){
String errorMsg ="未知错误";
if (einstanceof ConnectException){
errorMsg ="网络不可用";
}else if (einstanceof UnknownHostException) {
errorMsg ="未连接网络";
}else if (einstanceof SocketTimeoutException) {
errorMsg ="请求网络超时";
}else if (einstanceof HttpException) {
HttpException httpException = (HttpException) e;
errorMsg =convertStatusCode(httpException);
}else if (einstanceof ParseException || einstanceof JSONException
|| einstanceof JSONException) {
errorMsg ="数据解析错误";
}
return errorMsg;
}
private static String convertStatusCode(HttpException httpException) {
String msg;
if (httpException.code() >=500 && httpException.code() <600) {
msg ="服务器处理请求出错";
}else if (httpException.code() >=400 && httpException.code() <500) {
msg ="服务器无法处理请求";
}else if (httpException.code() >=300 && httpException.code() <400) {
msg ="请求被重定向到其他页面";
}else {
msg = httpException.message();
}
return msg;
}
}
interceptor包下都是写的一些拦截器,可先不做参考;
BaseObserver.class 服务器数据返回统一处理类
/**
* 数据返回统一处理 参考https://www.jianshu.com/p/ff619fea7e22
*
* @param
*/
public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {
private static final StringTAG ="BaseObserver";
@Override
public void onNext(BaseResponse<T> response) {
//在这边对 基础数据 进行统一处理 举个例子:
if (response.getRes_code() ==200) {
onSuccess(response.getDemo());
}else {
onFailure(null, response.getErr_msg(),false);
}
}
@Override
public void onError(Throwable e) {//服务器错误信息处理
onFailure(e, RxExceptionUtil.exceptionHandler(e),false);
}
@Override
public void onComplete() {
}
@Override
public void onSubscribe(Disposable d) {
onFailure(new UnknownHostException(), RxExceptionUtil.exceptionHandler(new UnknownHostException()),true);
}
public abstract void onSuccess(T result);
public abstract void onFailure(Throwable e, String errorMsg,boolean isNoConnected);
}
ProgressObserver.class 加入加载loading
/**
* Observer加入加载框
*
* @param
*/
public abstract class ProgressObserver<T> extends BaseObserver<T> {
private boolean mShowDialog;
private ProgressDialogdialog;
private ContextmContext;
private Disposabled;
public ProgressObserver(Context context, Boolean showDialog) {
mContext = context;
mShowDialog = showDialog;
}
public ProgressObserver(Context context) {
this(context,false);
}
@Override
public void onSubscribe(Disposable d) {
this.d = d;
if (!isConnected(mContext)) {
Toast.makeText(mContext,"未连接网络!!", Toast.LENGTH_SHORT).show();
if (d.isDisposed()) {
d.dispose();
}
super.onSubscribe(d);
}else {
if (dialog ==null &&mShowDialog ==true) {
dialog =new ProgressDialog(mContext);
dialog.setMessage("正在加载中...");
dialog.show();
}
}
}
@Override
public void onError(Throwable e) {
if (d.isDisposed()) {
d.dispose();
}
hidDialog();
super.onError(e);
}
@Override
public void onComplete() {
if (d.isDisposed()) {
d.dispose();
}
hidDialog();
super.onComplete();
}
public void hidDialog() {
if (dialog !=null &&mShowDialog ==true)
dialog.dismiss();
dialog =null;
}
/**
* 是否有网络连接,不管是wifi还是数据流量
//可以写在工具类里
*
* @param context
* @return
*/
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info ==null) {
return false;
}
boolean available = info.isAvailable();
return available;
}
}
RxHelper.class 统一调度类
/**
* 调度类
*/
public class RxHelper {
public static <T> ObservableTransformer<T,T> observableIO2Main(final Context context) {
return upstream -> {
Observable<T> observable = upstream.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
return composeContext(context, observable);
};
}
public static <T> ObservableTransformer<T,T> observableIO2Main(final RxFragment fragment) {
return upstream -> upstream.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).compose(fragment.<T>bindToLifecycle());
}
public static <T> FlowableTransformer<T,T> flowableIO2Main() {
return upstream -> upstream
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
private static <T> ObservableSource<T> composeContext(Context context, Observable<T> observable) {
if (context instanceof RxActivity) {
return observable.compose(((RxActivity) context).bindUntilEvent(ActivityEvent.DESTROY));
}else if (context instanceof RxFragmentActivity) {
return observable.compose(((RxFragmentActivity) context).bindUntilEvent(ActivityEvent.DESTROY));
}else if (context instanceof com.trello.rxlifecycle2.components.support.RxAppCompatActivity) {
return observable.compose(((com.trello.rxlifecycle2.components.support.RxAppCompatActivity) context).bindUntilEvent(ActivityEvent.DESTROY));
}else if ((context instanceof RxAppCompatActivity)){
return observable.compose(((RxAppCompatActivity) context).bindUntilEvent(ActivityEvent.DESTROY));
}else {
return observable;
}
}
}
RetrofitManger.class 创建retorfit 网络请求统一处理
public class RetrofitManger {
/**
* 保存一个retrofit的实例,通过(baseUrl来获取)
*/
private HashMapmRetrofitHashMap =new HashMap<>();
private static final int DEFAULT_MILLISECONDS =10;//默认的超时时间
/**
* 内部类单例设计模式
*/
private RetrofitManger() {
}
private static class RetrofitMangerInstance {
private final static RetrofitMangerRETROFIT_MANGER =new RetrofitManger();
}
public static RetrofitManger getInstance() {
return RetrofitMangerInstance.RETROFIT_MANGER;
}
private Retrofit getRetrofit(String baseUrl) {
Retrofit retrofit;
if (mRetrofitHashMap.containsKey(baseUrl)) {
retrofit =mRetrofitHashMap.get(baseUrl);
}else {
retrofit = createRetrofit(baseUrl);
mRetrofitHashMap.put(baseUrl,retrofit);
}
return retrofit;
}
/**
* @Params :创建Retrofit
* @Author :zhaohuiming
* @Date :2019/12/10
*/
private Retrofit createRetrofit(String baseUrl) {
OkHttpClient httpClient =new OkHttpClient().newBuilder()
.readTimeout(DEFAULT_MILLISECONDS, TimeUnit.SECONDS)//设置读取超时时间
.connectTimeout(DEFAULT_MILLISECONDS, TimeUnit.SECONDS)//设置请求超时时间
.writeTimeout(DEFAULT_MILLISECONDS, TimeUnit.SECONDS)//设置写入超时时间
//.addInterceptor(new HeadersInterceptor())//添加公共头信息
//.addInterceptor(new LogInterceptor())//添加打印拦截器
.retryOnConnectionFailure(false)//设置出现错误进行重新连接。
.build();
return new Retrofit.Builder()
.client(httpClient)
.baseUrl(baseUrl)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
/**
* 根据各业务接口 获取不同的retrofit service接口对象
*/
public T getRetrofitService(Class<T> tClass) {
return getRetrofit(BaseApi.getBaseUrl()).create(tClass);
}
}
5.在业务组件里使用:
创建一个接口类,类如BookApiUrl 里面是请求接口 详细使用可查看retorfit得使用方式,下面只是举例说明
public interface BookApiUrl {
@GET(Constans.retrofit)
Call getRetrofit();
//第一种方式:GET不带参数
@GET("retrofit.txt")
Observable> getUser();
@GET
Observable getUser(@Url String url);
/**
* TODO POST请求
*/
//第一种方式:@Body
@Headers("Accept:application/json")
@POST("login")
Observable postUser(@Body RequestBody body);
}
BaseModule.class 页面类得创建请求对象,这个也可以放在moduleBase得https里面,传泛型创建
public class BaseModule {
public static ApiUrl createRetrofit(){
//BookApiUrl 这个根据页面模块得名称创建
return RetrofitManger.getInstance().getRetrofitService(BookApiUrl .class);
}
}
RequestUtils.class 调用工具类,对应每一个页面一个
public class RequestUtils {
/**
* Get 请求demo
*
* @param context
* @param observer
*/
public static void getDemo(BaseActivity context, ProgressObserver observer) {
BaseModule.createRetrofit()
.getDemo()
.compose(RxHelper.observableIO2Main(context))
.subscribe(observer);
}
/**
* Post 请求demo
* @param context
* @param consumer
*/
public static void postDemo(BaseActivity context, String name, String password, ProgressObserver consumer) {
BaseModule.createRetrofit()
.postUser(name, password).compose(RxHelper.observableIO2Main(context))
.subscribe(consumer);
}
}
最后一步就是在你们得Activity或者fragment里面需要调用请求网络的地方调用就行了
例如:
private void getData() {
RequestUtils.getDemo(this,new ProgressObserver(this) {
@Override
public void onSuccess(Demo result) {
tv_retrofit.setText(result.toString());
}
@Override
public void onFailure(Throwable e, String errorMsg,boolean isNoConnected) {
tv_retrofit.setText(errorMsg);
}
});
}
private void getPostDemo() {
RequestUtils.postDemo(this,"name","111",new ProgressObserver(this) {
@Override
public void onSuccess(Demo result) {
}
@Override
public void onFailure(Throwable e, String errorMsg,boolean isNoConnected) {
}
});
}
结束,谢谢观看,有问题及时留言探讨,不喜勿喷谢谢;