很多朋友接手项目都开始带有Retrofit +Okhttp+RxJava搭建的网络请求框架,甚至有的还在尝试准备使用这个,接下来就来介绍一下这个网络请求框架的大致使用方法,和具体搭建方法。
直接上代码,首先是BaseView
publicinterfaceBaseView1 {
/**
* 显示操作进度
*/
publicvoidshowProgress();
/**
* 关闭进度
*/
publicvoidcloseProgress();
/**
* 成功回调
*/
publicvoidexcuteErrSuccessCallBack(String s);
/**
* 失败回调
*/
publicvoidexcuteErrFailedCallBack(String s);
}
然后就是写实现BaseView的Api了,一般是将自己网络请求原地址写上去
importandroid.os.Build;
importcom.google.gson.Gson;
importcom.google.gson.GsonBuilder;
importcom.lvgou.distribution.bean.CallBackVo;
importcom.lvgou.distribution.presenter.ErrorLogPresenter;
importcom.lvgou.distribution.view.BaseView1;
importcom.squareup.okhttp.OkHttpClient;
importjava.util.concurrent.TimeUnit;
importretrofit.GsonConverterFactory;
importretrofit.Retrofit;
importretrofit.RxJavaCallAdapterFactory;
importrx.Subscriber;
/**
* Created by Administrator on 2016/9/9.
*/
publicclassApiimplementsBaseView1 {
privatestaticApi ourInstance;
privateIServiceAPI gankService;
privateErrorLogPresenter errorLogPresenter;
publicstaticApi getInstance() {
if(ourInstance ==null) ourInstance =newApi();
returnourInstance;
}
publicbooleanisOne =true;
privateApi() {
OkHttpClient okHttpClient =newOkHttpClient();
okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);
errorLogPresenter =newErrorLogPresenter(this);
isOne =true;
/*
* 查看网络请求发送状况
*/
// if (EasyApplication.getInstance().log) {
// okHttpClient.interceptors().add(chain -> {
// Response response = chain.proceed(chain.request());
// com.orhanobut.logger.Logger.d(chain.request().urlString());
// return response;
// });
// }
Gson mGson =newGsonBuilder()
.registerTypeAdapter(String.class,newDeserializerData())
.create();
Retrofit retrofit =newRetrofit.Builder().baseUrl("原网络请求地址")
.addCallAdapterFactory(
RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(mGson))
.client(okHttpClient)
.build();
this.gankService = retrofit.create(IServiceAPI.class);
}
publicIServiceAPI getGankService() {
returngankService;
}
/**
* 创建 Subscriber
*
* @param mICallBackListener
* @return Subscriber
*/
publicSubscriber createSubscriber(finalICallBackListener mICallBackListener) {
Subscriber mSubscriber =newSubscriber() {
@Override
publicvoidonCompleted() {
// Log.i(TAG, "[onCompleted]");
}
@Override
publicvoidonError(Throwable e) {
// Log.e(TAG, "[onError]" + e.getMessage());
CallBackVo mCallBackVo =newCallBackVo();
// mCallBackVo.setResCode("400");
// mCallBackVo.setResMsg("请求失败");
// mCallBackVo.setResObj(null);
return;
}
@Override
publicvoidonNext(String s) {
Gson gosn =newGson();
CallBackVo mCallBackVo = gosn.fromJson(s, CallBackVo.class);
if(mCallBackVo.getStatus().equals("1")) {
mICallBackListener.onSuccess(s);
}else{
mICallBackListener.onFaild(mCallBackVo.getMessage());
}
}
};
returnmSubscriber;
}
@SuppressWarnings("static-access")
publicstaticString GetDeviceName() {
returnnewBuild().MODEL;
}
@Override
publicvoidshowProgress() {
}
@Override
publicvoidcloseProgress() {
}
@Override
publicvoidexcuteErrSuccessCallBack(String s) {
}
@Override
publicvoidexcuteErrFailedCallBack(String s) {
}
}
这样就完成了第一步,接下来就是网上很多的retrofit的运用,怎么去传递参数问题,对于这个我只是举例我post上传的方式,其它的去网上其它位子copy一下就行了
publicinterfaceIServiceAPI {
@FormUrlEncoded
@POST("网络请求链接尾")
Observable shareMedal(@Field("参数名字") String 参数值,@Field("参数名字") String 参数值);
}
剩下就来看怎么去调用这个网络请求了
publicclassShareMedalImplimplementsShareMedalModel {
@Override
publicvoidshareMedal(String 参数值,String 参数值, ICallBackListener callBackListener) {
IServiceAPI mIServiceAPI = Api.getInstance().getGankService();
mIServiceAPI.shareMedal(参数值, 参数值)
// Subscriber前面执行的代码都是在I/O线程中运行
.subscribeOn(Schedulers.io())
// 操作observeOn之后操作主线程中运行.
.observeOn(AndroidSchedulers.mainThread())
.subscribe(Api.getInstance().createSubscriber(callBackListener));
}
}
这个就是调用第一步,获取到callback,然后进行post那边的调用
后面那个Model实际就是一个interface,就写上
voidshareMedal(String 参数值,String 参数值, ICallBackListener callBackListener);
这个方法而已
接下来就是presenter层了,也就是最后层,就是对上面的这些的调用,然后想办法返回出去自己请求网络的结果,是失败还是成功什么的。
publicclassShareMedalPresenterextendsBasePresenter {
privateShareMedalImpl shareMedalImpl;
privateShareMedalView shareMedalView;
privateHandler mHandler;
publicShareMedalPresenter(ShareMedalView shareMedalView) {
this.shareMedalView = shareMedalView;
shareMedalImpl =newShareMedalImpl();
mHandler =newHandler(Looper.getMainLooper());
}
publicvoidshareMedal(String 参数, String 参数) {
shareMedalImpl.shareMedal(参数,参数,newICallBackListener() {
@Override
publicvoidonSuccess(finalString s) {
mHandler.post(newRunnable() {
@Override
publicvoidrun() {
shareMedalView.closeShareMedalProgress();
shareMedalView.OnShareMedalSuccCallBack("1", s);
}
});
}
@Override
publicvoidonFaild(finalString s) {
mHandler.post(newRunnable() {
@Override
publicvoidrun() {
shareMedalView.closeShareMedalProgress();
shareMedalView.OnShareMedalFialCallBack("1", s);
}
});
}
});
}
}
接下来要写的ShareMedalView这个也就是你调用实例化presenter位子要实现这个接口,然后实现方法的位子,就是new Presenter(this),这里this是让当前类实现方法,会实现三个方法,也就是下面view要写出来的抽象方法:
publicinterfaceShareMedalView {
/**
* 成功回调
*
* @param state
* @param respanse
*/
voidOnShareMedalSuccCallBack(String state, String respanse);
/**
* 失败回调
*
* @param state
* @param respanse
*/
voidOnShareMedalFialCallBack(String state, String respanse);
/**
* 关闭弹窗
*/
voidcloseShareMedalProgress();
}
对了,钓了一个basepresenter,这个也就是一个基类,写上也无妨
[java]view plaincopy
publicabstractclassBasePresenter {
publicT mView;
publicCompositeSubscription mCompositeSubscription;
publicDataManager mDataManager;
publicvoidattach(T mView){
this.mView=mView;
this.mCompositeSubscription =newCompositeSubscription();
// this.mDataManager = DataManager.getInstance();
}
publicvoiddettach(){
mView=null;
this.mCompositeSubscription.unsubscribe();
this.mCompositeSubscription =null;
// this.mDataManager = null;
}
publicbooleanisViewAttached() {
returnmView !=null;
}
publicT getMvpView() {
returnmView;
}
}
调用的时候实例化
shareMedalPresenter = new ShareMedalPresenter(this);
shareMedalPresenter .sharemedal()方法就行了
哈哈,就这么简单,再也不要为Retrofit+Okhttp+RxJava这个框架烦恼了,其实也没什么高端的,不会用的时候永远觉得遥不可及,当切身使用就觉得没什么难的了。
csdn项目地址:http://blog.csdn.net/greatdaocaoren/article/details/74555729