OkHttp简化请求封装思路
對(duì)于OKHttp的封裝,現(xiàn)在已經(jīng)有很多方法,甚至Retrofit也是基于OkHttp封裝而來。本文的封裝方式不一定是最好的,但相信在某一種場(chǎng)景下肯定能幫助你大大簡(jiǎn)化代碼。
一個(gè)普通的請(qǐng)求如下,采用了鏈?zhǔn)秸{(diào)用,使得可讀性大大增加。但是如果一個(gè)頁面里面有多個(gè)請(qǐng)求,代碼量也是多很多,而每次請(qǐng)求都要傳遞參數(shù)字段,假如某個(gè)字母錯(cuò)了也要回到相應(yīng)的界面查找。這對(duì)于代碼強(qiáng)迫癥來說是有點(diǎn)接受不了的。
OkHttpUtils.get().url(UrlAddress.GET_SCENIC_SPOTS).addHeader("authorization",GlobalParams.authorization).addParams("page","1").addParams("pageNum","99999").build().execute(new LiStringCallback() {@Overridepublic void onBefore(Request request, int id) {super.onBefore(request, id);// showLoadingDialog("獲取景區(qū)中");}@Overridepublic void onAfter(int id) {super.onAfter(id);// hideLoadingDialog();}@Overridepublic void onError(Call call, Exception e, int i) {super.onError(call, e, i);}@Overridepublic void onResponse(String s, int i) {super.onResponse(s, i);Gson gson = new Gson();//景區(qū)列表SceneSpotListResult result = gson.fromJson(s, SceneSpotListResult.class);if (result.checkCode()){sceneList.clear();sceneList.addAll(result.getResult().getData());}}});}復(fù)制代碼簡(jiǎn)化思路如下,先創(chuàng)建OKHttp封裝的接口監(jiān)聽LiOKHttpListen
/*** Created by li on 2018/4/10.* 這是OKHttp封裝的接口監(jiān)聽*/public interface LiOKHttpListen {/*** 訪問前* @param request 請(qǐng)求數(shù)據(jù)* @param requestType 操作類型*/void onHttpBefore(Request request,RequestType requestType);/*** 訪問后* @param requestType 操作類型*/void onHttpAfter(RequestType requestType);/*** 出錯(cuò)* @param e 異常信息* @param requestType 操作類型*/void onHttpError(Exception e,RequestType requestType);/*** 成功* @param s 服務(wù)器返回?cái)?shù)據(jù)* @param requestType 操作類型*/void onHttpResponse(String s,RequestType requestType); }復(fù)制代碼再創(chuàng)建自定義的回調(diào)LiStringCallback
/*** Created by li on 2018/4/9.* 自定義回調(diào)* 對(duì)接口的回調(diào)統(tǒng)一在這里進(jìn)行。*/public abstract class LiStringCallback extends StringCallback {//大帥比的接口private LiOKHttpListen liOKHttpListen;//大帥比的操作枚舉類型private RequestType requestType;//普通構(gòu)造方法public LiStringCallback() {}//帶有接口的構(gòu)造方法public LiStringCallback(LiOKHttpListen liOKHttpListen,RequestType requestType) {this.liOKHttpListen = liOKHttpListen;this.requestType = requestType;}//請(qǐng)求前操作@Overridepublic void onBefore(Request request, int id) {super.onBefore(request, id);if (liOKHttpListen != null) {liOKHttpListen.onHttpBefore(request,requestType);}}//請(qǐng)求結(jié)束后操作@Overridepublic void onAfter(int id) {super.onAfter(id);if (liOKHttpListen != null) {liOKHttpListen.onHttpAfter(requestType);}}//請(qǐng)求錯(cuò)誤操作@Overridepublic void onError(Call call, Exception e, int i) {//提示網(wǎng)絡(luò)異常MainApp.getInstance().showMsg(R.string.common_string_http_error);if (liOKHttpListen != null) {liOKHttpListen.onHttpError(e,requestType);}}//請(qǐng)求成功操作@Overridepublic void onResponse(String s, int i) {if (liOKHttpListen != null) {liOKHttpListen.onHttpResponse(s,requestType);}} } 復(fù)制代碼設(shè)置不同操作的枚舉類型,RequestType的作用是同個(gè)請(qǐng)求可能有不同的操作,需要對(duì)之進(jìn)行區(qū)分
/*** Created by li on 2018/4/10.* 枚舉類。包括需要進(jìn)行的操作,用于判斷不同操作*/public enum RequestType {GET_SCENE // 獲取景存放鍵值對(duì)數(shù)據(jù)的實(shí)體,僅方便數(shù)組請(qǐng)求/*** Created by li on 2018/4/10.* 存放鍵值對(duì)數(shù)據(jù)的實(shí)體*/public class LiKeyBean {//鍵名String keyName;//鍵值String keyValue;public LiKeyBean(String keyName, String keyValue) {this.keyName = keyName;this.keyValue = keyValue;}public String getKeyName() {return keyName;}public void setKeyName(String keyName) {this.keyName = keyName;}public String getKeyValue() {return keyValue;}public void setKeyValue(String keyValue) {this.keyValue = keyValue;} }復(fù)制代碼最后是okhttp管理類
/*** Created by li on 2018/4/10.* 面對(duì)用戶使用的方法,可用post等方法* 用戶調(diào)用對(duì)應(yīng)方法,并實(shí)現(xiàn)接口即可*/public class LiOKHttpUtil {/*** 用數(shù)據(jù)請(qǐng)求 post* @param listen 實(shí)現(xiàn)LiOKHttpListen接口的對(duì)象* @param url 鏈接* @param heads 請(qǐng)求頭數(shù)組* @param params 參數(shù)數(shù)組* @param requestType 操作類型*/private static void post(LiOKHttpListen listen,String url,LiKeyBean[] heads, LiKeyBean[] params ,RequestType requestType){//獲取buildPostFormBuilder postFormBuilder = OkHttpUtils.post().url(url);//添加請(qǐng)求頭if (heads!=null){for (int i=0;i<heads.length;i++){LiKeyBean keyBean = heads[i];if (keyBean==null) continue;postFormBuilder.addHeader(keyBean.getKeyName(),keyBean.getKeyValue());}}//添加請(qǐng)求if (params!=null){for (int i=0;i<params.length;i++){LiKeyBean keyBean = params[i];if (keyBean==null) continue;postFormBuilder.addParams(keyBean.getKeyName(),keyBean.getKeyValue());}}//請(qǐng)求postFormBuilder .build().execute(new LiStringCallback(listen,requestType) {@Overridepublic void onBefore(Request request, int id) {super.onBefore(request, id);}@Overridepublic void onAfter(int id) {super.onAfter(id);}@Overridepublic void onError(Call call, Exception e, int i) {super.onError(call, e, i);}@Overridepublic void onResponse(String s, int i) {super.onResponse(s, i);}});}/*** 用數(shù)據(jù)請(qǐng)求 get* @param listen 實(shí)現(xiàn)LiOKHttpListen接口的對(duì)象* @param url 鏈接* @param heads 請(qǐng)求頭數(shù)組* @param params 參數(shù)數(shù)組* @param requestType 操作類型*/private static void get(LiOKHttpListen listen, String url,LiKeyBean[] heads, LiKeyBean[] params ,RequestType requestType){//獲取buildGetBuilder getBuilder = OkHttpUtils.get().url(url);//添加請(qǐng)求頭if (heads!=null){for (int i=0;i<heads.length;i++){LiKeyBean keyBean = heads[i];if (keyBean==null) continue;getBuilder.addHeader(keyBean.getKeyName(),keyBean.getKeyValue());}}//添加請(qǐng)求if (params!=null){for (int i=0;i<params.length;i++){LiKeyBean keyBean = params[i];if (keyBean==null) continue;getBuilder.addParams(keyBean.getKeyName(),keyBean.getKeyValue());}}//請(qǐng)求getBuilder .build().execute(new LiStringCallback(listen,requestType) {@Overridepublic void onBefore(Request request, int id) {super.onBefore(request, id);}@Overridepublic void onAfter(int id) {super.onAfter(id);}@Overridepublic void onError(Call call, Exception e, int i) {super.onError(call, e, i);}@Overridepublic void onResponse(String s, int i) {super.onResponse(s, i);}});}/*** 用事先封裝好的GetBuilder進(jìn)行g(shù)et請(qǐng)求* @param listen 實(shí)現(xiàn)LiOKHttpListen接口的對(duì)象* @param getBuilder 事先封裝好的GetBuilder* @param requestType 操作類型*/private static void get(LiOKHttpListen listen,GetBuilder getBuilder ,RequestType requestType){//請(qǐng)求getBuilder.build().execute(new LiStringCallback(listen,requestType) {@Overridepublic void onBefore(Request request, int id) {super.onBefore(request, id);}@Overridepublic void onAfter(int id) {super.onAfter(id);}@Overridepublic void onError(Call call, Exception e, int i) {super.onError(call, e, i);}@Overridepublic void onResponse(String s, int i) {super.onResponse(s, i);}});}/*** 用事先封裝好的PostFormBuilder進(jìn)行post請(qǐng)求* @param listen 實(shí)現(xiàn)LiOKHttpListen接口的對(duì)象* @param postFormBuilder 事先封裝好的PostFormBuilder* @param requestType 操作類型*/private static void post(LiOKHttpListen listen,PostFormBuilder postFormBuilder ,RequestType requestType){//請(qǐng)求postFormBuilder.build().execute(new LiStringCallback(listen,requestType) {@Overridepublic void onBefore(Request request, int id) {super.onBefore(request, id);}@Overridepublic void onAfter(int id) {super.onAfter(id);}@Overridepublic void onError(Call call, Exception e, int i) {super.onError(call, e, i);}@Overridepublic void onResponse(String s, int i) {super.onResponse(s, i);}});}/*** 獲取景區(qū)* @param listen*/public static void getScenes(LiOKHttpListen listen,RequestType requestType) {GetBuilder getBuilder = OkHttpUtils.get().url(UrlAddress.GET_SCENIC_SPOTS).addHeader("authorization",GlobalParams.authorization).addParams("page","1").addParams("string","99999");get(listen,getBuilder,requestType);}}復(fù)制代碼到這一步就可以在activity里面請(qǐng)求了
public class MainActivity extends BaseActivity implements LiOKHttpListen {@Overrideprotected int getLayoutId() {return R.layout.main_activity_main;}@Overrideprotected void initViews() {}@Overrideprotected void onDestroy() {}@Overrideprotected void initDatas() {getScenes();}@Overrideprotected void showContent() {}/*** 獲取全部景區(qū)*/public void getScenes(){//一行代碼就可以請(qǐng)求LiOKHttpUtil.getScenes(this,RequestType.GET_SCENE);}@Overridepublic void onHttpBefore(Request request, RequestType requestType) {switch (requestType){case GET_SCENE:showLoadingDialog("獲取景區(qū)中");break;}}@Overridepublic void onHttpAfter(RequestType requestType) {//隱藏彈窗hideLoadingDialog();}@Overridepublic void onHttpError(Exception e, RequestType requestType) {}@Overridepublic void onHttpResponse(String s, RequestType requestType) {switch (requestType){case GET_SCENE://獲取成功后的操作break;}}}復(fù)制代碼通過以上操作就實(shí)現(xiàn)了筆者想要的目的,總結(jié)如下 1.拋棄了原本單個(gè)請(qǐng)求就可以看到全部處理的可讀性,改成了全部請(qǐng)求通過接口返回,適用于大部分對(duì)除response之外操作不多或者重復(fù)的請(qǐng)求 2.將所有請(qǐng)求的大任都交給了LiOkHttpUtil的工具類,方便對(duì)請(qǐng)求管理
總結(jié)
以上是生活随笔為你收集整理的OkHttp简化请求封装思路的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hdu-1796 How many in
- 下一篇: VisualSVN安装配置与使用