標籤:
概述
在android開發中經常要訪問網路,目前最流行的網路訪問架構就是Okhttp了,然而我們在具體使用時,往往仍然需要二次封裝。我使用Builder設計模式進行了封裝形成oknet開源庫。
介紹 oknet是一套基於okhttp的android網路http架構,封裝了請求參數處理,日誌列印。Github地址
https://github.com/vir56k/oknet
特性
1.簡潔的文法2.支援自訂處理 message code 不等於0 的情形3.支援檔案上傳4.完整清晰的log日誌輸出5.支援 公用參數 的配置6.支援每個http請求的 日誌 記錄7.支援 預設異常 的處理8.支援 移除檔案下載(通過FileDownloader)
適用情境
和服務端產生約定:
響應的json格式一定為:{code:0, msg:"", body:""}1.服務端 響應成功 則返回對應的json2.code=0表示成功,body裡如正確響應json.3.code非零表示失敗,msg表示失敗的文本。4.body 節點裡放置你的自訂json資料
引用
在你的項目的根目錄下的 build.gradle 檔案中添加引用
compile ‘zhangyf.vir56k:oknet:0.0.1‘
樣本:
dependencies { compile fileTree(dir: ‘libs‘, include: [‘*.jar‘]) compile ‘zhangyf.vir56k:oknet:0.0.1‘}
在系統啟動時進行一些配置
比如在你的繼承自Application的子類中,或者主Activity啟動時配置。
//配置okhttp 緩衝位置 OknetConfig.setExternalCacheDir(getExternalCacheDir()); //OknetConfig.setRequestParaInterceptor(new CustomRequestParaInterceptor1()); OknetConfig.setRequestParaInterceptor(new CustomRequestParaInterceptor_jlb_app()); OknetConfig.setDefaultExceptionHandler(new CustomDefalutExceptionHandler()); OknetConfig.setLogInterceptor(new LogInterceptor() { @Override public void onLog(String tag, String msg) { //Log.i("日誌攔截器攔截到 tag =" + tag, " msg = " + msg); } });
post簡單請求,和String類型的響應
RequestBuilder.with(getActivity()).URL(Apis.GAEA_URLS.CAB_ADVERT_LIST). onSuccess(new CommonCallback<String>(String.class) { @Override public void onSuccess(String result, CommonMessage responseMessage, String responseString) { Log.i(TAG, "==成功:" + result); alert("==成功"); } }).excute();
帶參數的請求,和 Json序列化的回調
Type t = new TypeToken<List<Demo2Cell>>() { }.getType(); RequestBuilder.with(getActivity()) .URL(Apis.Cab_Urls.GET_BOX_FREE_NEWS) .para("cabinet_code", "1412345678") .onSuccess(new CommonCallback<List<Demo2Cell>>(t) { @Override public void onSuccess(List<Demo2Cell> result, CommonMessage responseMessage, String responseString) { Log.i(TAG, "!!! 成功:" + result.get(0)); alert("!!成功" + result.get(0)); } }) .excute();
自訂處理異常代碼(服務返回的訊息裡的 message code 不等於0) 的情形
RequestBuilder.with(getActivity()) .URL(Apis.GAEA_URLS.CAB_ADVERT_LIST) .onSuccess(new CommonCallback<String>(String.class) { @Override public void onSuccess(String result, CommonMessage responseMessage, String responseString) { Log.i(TAG, "==成功:" + result); alert("==成功"); } @Override public boolean onFailure(int httpCode, Exception ex, CommonMessage responseMessage, String responseString) { if (ex instanceof NoZeroException) { NoZeroException noZeroException = (NoZeroException) ex; int code = noZeroException.getCode(); Log.i(TAG, "!!!!!!!!失敗:" + noZeroException); alert("!!!!!!!!!!!!!!!!失敗," + noZeroException); //return false;//如果不需要 預設異常處理器再次處理,這裡可以返回true } return super.onFailure(httpCode, ex, responseMessage, responseString); } }) .excute();
上傳檔案
File f = new File(Environment.getExternalStorageDirectory().getPath(), "ImageCache/CloseIcon.png"); if (!f.exists()) throw new RuntimeException("not found ImageCache/CloseIcon.png"); RequestBuilder.with(getActivity()) .URL("http://10.0.1.232:8888/uc/suser/upload_avatar") .para("uid", "100202") .para("sid", "50e2904ca493d5d25475e4e080858925") /************************ 威力僅僅在這一行,其他都一樣 ***************************/ .file("file", f) /************************ 威力僅僅在這一行,其他都一樣 ***************************/ .onSuccess(new CommonCallback<Demo3Bean>(Demo3Bean.class) { @Override public void onSuccess(Demo3Bean result, CommonMessage responseMessage, String responseString) { Log.i(TAG, "!!! 成功:" + result.count); alert("!!成功" + result.count); } }) .excute();
處理需要顯示進度條的情形
RequestBuilder.with(getActivity()) .URL(Apis.GAEA_URLS.CAB_NOTICE_LIST) .para("cabinet_code", "1412345678") /******** 沒錯,你沒有看錯,僅僅 下面 一行,進度條就閃亮登場 ************/ .progress(new DialogProgressIndicator(getActivity())) /******** 沒錯,你沒有看錯,僅僅 上面 一行,進度條就閃亮登場 ************/ .onSuccess(new CommonCallback<Demo3Bean>(Demo3Bean.class) { @Override public void onSuccess(Demo3Bean result, CommonMessage responseMessage, String responseString) { Log.i(TAG, "!!! 成功:" + result.count); alert("!!成功" + result.count); } }) .excute();
同步的方式發送http請求
private void demo_syncExcuete() { new AsyncTask<Void, Void, Void>() { boolean isok; String mResult1; @Override protected Void doInBackground(Void... params) { RequestBuilder.with(getActivity()) .URL(Apis.GAEA_URLS.CAB_ADVERT_LIST) .para("cabinet_code", "1412345678") .onSuccess(new CommonCallback<String>(String.class) { @Override public void onSuccess(String result, CommonMessage responseMessage, String responseString) { isok = true; mResult1 = result; } @Override public boolean onFailure(int httpCode, Exception exception, CommonMessage responseMessage, String allResponseString) { isok = false; return super.onFailure(httpCode, exception, responseMessage, allResponseString); } }) .syncExcute(); return null; } @Override protected void onPostExecute(Void aVoid) { if (isok) { Log.i(TAG, "==成功:" + mResult1); alert("==成功"); } } }.execute();}
下載檔案
public static void downloadFileDemo() { String url = "http://d.hiphotos.baidu.com/zhidao/pic/item/08f790529822720e67a9065978cb0a46f21fab2a.jpg"; File dest = new File(Environment.getExternalStorageDirectory(), "6f21fab2a.jpg"); FileDownloader.downloadFile(url, dest, new FileDownloader.DownloadFileProgressListener2() { @Override public void onFailure(Call call, IOException e) { System.out.println("Err: " + e.getMessage()); } @Override public void onProgress(long bytesRead, long contentLength, boolean done) { System.out.println(String.format("檔案下載進度, read %s/%s", bytesRead, contentLength)); } @Override protected void onSuccess(Call call, File file) { System.out.println("檔案下載成功嗎 =" + file.exists()); } });}
android 開發 - 使用okhttp架構封裝的開發架構