Retrofit+Okhttp+RxJava

很多朋友接手項目都開始帶有Retrofit +Okhttp+RxJava搭建的網(wǎng)絡請求框架,甚至有的還在嘗試準備使用這個,接下來就來介紹一下這個網(wǎng)絡請求框架的大致使用方法,和具體搭建方法。

直接上代碼,首先是BaseView

publicinterfaceBaseView1?{

/**

*?顯示操作進度

*/

publicvoidshowProgress();

/**

*?關(guān)閉進度

*/

publicvoidcloseProgress();

/**

*?成功回調(diào)

*/

publicvoidexcuteErrSuccessCallBack(String?s);

/**

*?失敗回調(diào)

*/

publicvoidexcuteErrFailedCallBack(String?s);

}

然后就是寫實現(xiàn)BaseView的Api了,一般是將自己網(wǎng)絡請求原地址寫上去

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;

/*

*?查看網(wǎng)絡請求發(fā)送狀況

*/

//????????????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("原網(wǎng)絡請求地址")

.addCallAdapterFactory(

RxJavaCallAdapterFactory.create())

.addConverterFactory(GsonConverterFactory.create(mGson))

.client(okHttpClient)

.build();

this.gankService?=?retrofit.create(IServiceAPI.class);

}

publicIServiceAPI?getGankService()?{

returngankService;

}

/**

*?創(chuàng)建?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)?{

}

}

這樣就完成了第一步,接下來就是網(wǎng)上很多的retrofit的運用,怎么去傳遞參數(shù)問題,對于這個我只是舉例我post上傳的方式,其它的去網(wǎng)上其它位子copy一下就行了

publicinterfaceIServiceAPI?{

@FormUrlEncoded

@POST("網(wǎng)絡請求鏈接尾")

Observable?shareMedal(@Field("參數(shù)名字")?String?參數(shù)值,@Field("參數(shù)名字")?String?參數(shù)值);

}

剩下就來看怎么去調(diào)用這個網(wǎng)絡請求了

publicclassShareMedalImplimplementsShareMedalModel?{

@Override

publicvoidshareMedal(String?參數(shù)值,String?參數(shù)值,?ICallBackListener?callBackListener)?{

IServiceAPI?mIServiceAPI?=?Api.getInstance().getGankService();

mIServiceAPI.shareMedal(參數(shù)值,?參數(shù)值)

//?Subscriber前面執(zhí)行的代碼都是在I/O線程中運行

.subscribeOn(Schedulers.io())

//?操作observeOn之后操作主線程中運行.

.observeOn(AndroidSchedulers.mainThread())

.subscribe(Api.getInstance().createSubscriber(callBackListener));

}

}

這個就是調(diào)用第一步,獲取到callback,然后進行post那邊的調(diào)用

后面那個Model實際就是一個interface,就寫上

voidshareMedal(String?參數(shù)值,String?參數(shù)值,?ICallBackListener?callBackListener);

這個方法而已

接下來就是presenter層了,也就是最后層,就是對上面的這些的調(diào)用,然后想辦法返回出去自己請求網(wǎng)絡的結(jié)果,是失敗還是成功什么的。

publicclassShareMedalPresenterextendsBasePresenter?{

privateShareMedalImpl?shareMedalImpl;

privateShareMedalView?shareMedalView;

privateHandler?mHandler;

publicShareMedalPresenter(ShareMedalView?shareMedalView)?{

this.shareMedalView?=?shareMedalView;

shareMedalImpl?=newShareMedalImpl();

mHandler?=newHandler(Looper.getMainLooper());

}

publicvoidshareMedal(String?參數(shù),?String?參數(shù))?{

shareMedalImpl.shareMedal(參數(shù),參數(shù),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這個也就是你調(diào)用實例化presenter位子要實現(xiàn)這個接口,然后實現(xiàn)方法的位子,就是new ?Presenter(this),這里this是讓當前類實現(xiàn)方法,會實現(xiàn)三個方法,也就是下面view要寫出來的抽象方法:

publicinterfaceShareMedalView?{

/**

*?成功回調(diào)

*

*?@param?state

*?@param?respanse

*/

voidOnShareMedalSuccCallBack(String?state,?String?respanse);

/**

*?失敗回調(diào)

*

*?@param?state

*?@param?respanse

*/

voidOnShareMedalFialCallBack(String?state,?String?respanse);

/**

*?關(guān)閉彈窗

*/

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;

}

}

調(diào)用的時候?qū)嵗?/p>

shareMedalPresenter = new ShareMedalPresenter(this);

shareMedalPresenter .sharemedal()方法就行了

哈哈,就這么簡單,再也不要為Retrofit+Okhttp+RxJava這個框架煩惱了,其實也沒什么高端的,不會用的時候永遠覺得遙不可及,當切身使用就覺得沒什么難的了。


csdn項目地址:http://blog.csdn.net/greatdaocaoren/article/details/74555729

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容