在android開發中常常要訪問網絡,目前最流行的網絡訪問框架就是Okhttp了,然而咱們在具體使用時,每每仍然須要二次封裝。我使用Builder設計模式進行了封裝造成oknet開源庫。android
https://github.com/vir56k/oknetgit
1.簡潔的語法 2.支持自定義處理 message code 不等於0 的情形 3.支持文件上傳 4.完整清晰的log日誌輸出 5.支持 公共參數 的配置 6.支持每一個http請求的 日誌 記錄 7.支持 默認異常 的處理 8.支持 移除文件下載(經過FileDownloader)
和服務端產生約定:github
響應的json格式必定爲:{code:0, msg:"", body:""} 1.服務端 響應成功 則返回對應的json 2.code=0表示成功,body裏如正確響應json. 3.code非零表示失敗,msg表示失敗的文本。 4.body 節點裏放置你的自定義json數據
在你的項目的根目錄下的 build.gradle 文件中添加引用json
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); } });
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();
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();
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();
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()); } }); }