An overview of the

The most popular network access framework is Okhttp. However, when we use it, we often need secondary encapsulation. I use the Builder design mode for encapsulation to form okNET open source library.

introduce

Oknet is a set of ANDROID network HTTP framework based on OKHTTP, encapsulates the request parameter processing, log printing.

Name: oknet making address: https://github.com/vir56k/oknet author: zhangyunfeiVirCopy the code

features

1. Concise syntax 2. Support custom handling of situations where Message code is not equal to 0 3. Upload files 4. Output complete and clear logs 5. Configure public parameters 6. Support logging of each HTTP request 7. Support handling of default exceptions 8. Support for removing file downloads (via FileDownloader)

Applicable scenario

Generate a convention message structure with the server:

The returned response must be in json format:

{code:0, MSG :"", body:""} Parameter description: 1. If the response is successful, the server returns the corresponding JSON. 2. Code =0 indicates that the response is successful. 4. Place your custom JSON data in the body nodeCopy the code

reference

Add the reference to the build.gradle file at the root of your project

The compile 'zhangyf. Vir56k: oknet: 0.0.1'Copy the code

Example:

Dependencies {the compile fileTree (dir: 'libs', include: [' *. Jar']) compile 'zhangyf. Vir56k: oknet: 0.0.1'}Copy the code

Do some configuration when the system starts up

For example, in your subclass that inherits from Application, or when the main Activity starts.

/ / configuration okhttp cache location 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 (" MSG =" + tag, "MSG =" + MSG); }});Copy the code

Post simple request, and String response

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, "== successful :" + result); Alert (" = = success "); } }).excute();Copy the code

Request with parameters, and callback to Json serialization

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();Copy the code

Custom handling of exception codes where message code does not equal 0 in a message returned by the service

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, "== successful :" + result); Alert (" = = success "); } @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, "!!!!!!!! Failed :" + noZeroException); alert("!!!!!!!!!!!!!!!! Failed," + noZeroException); //return false; } return super.onFailure(httpCode, ex, responseMessage, responseString); } }) .excute();Copy the code

Upload a file

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", "50 e2904ca493d5d25475e4e080858925") / * * * * * * * * * * * * * * * * * * * * * * * * power just in this line, the other is the same * * * * * * * * * * * * * * * * * * * * * * * * * * * /. The file (" file ", F) / * * * * * * * * * * * * * * * * * * * * * * * * power just in this line, the other is the same * * * * * * * * * * * * * * * * * * * * * * * * * * * /. 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();Copy the code

Handles situations where a progress bar needs to be displayed

RequestBuilder.with(getActivity()) .URL(Apis.GAEA_URLS.CAB_NOTICE_LIST) .para("cabinet_code", "1412345678") /******** yes, you read that right, just the following line, ************/. 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();Copy the code

The DialogProgressIndicator class here is a “progress bar indicator” object.

Sends HTTP requests synchronously

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, "== successful :" + mResult1); Alert (" = = success "); } } }.execute(); }Copy the code

The download file

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(" File download progress, read %s/%s", bytesRead, contentLength)); } @override protected void onSuccess(Call Call, File File) {system.out.println (" did the File download successfully =" + file.exists()); }}); }Copy the code