Android Development-Development framework using the OKHTTP framework package

Source: Internet
Author: User

Overview

In Android development often to access the network, the current most popular network access framework is okhttp, however, we use in the specific, often still need two times package. I used the builder design pattern to encapsulate the form of the Oknet Open Source Library.

IntroducedOknet is a set of Okhttp-based Android network HTTP framework that encapsulates request parameter handling and log printing. GitHub Address

Https://github.com/vir56k/oknet

Characteristics
1.简洁的语法2.支持自定义处理 message code 不等于0 的情形3.支持文件上传4.完整清晰的log日志输出5.支持 公共参数 的配置6.支持每个http请求的 日志 记录7.支持 默认异常 的处理8.支持 移除文件下载(通过FileDownloader)
Applicable scenarios

and server-side generation conventions:

响应的json格式一定为:{code:0,   msg:"", body:""}1.服务端 响应成功 则返回对应的json2.code=0表示成功,body里如正确响应json.3.code非零表示失败,msg表示失败的文本。4.body 节点里放置你的自定义json数据
Reference

Add a reference to the Build.gradle file in the root directory of your project

compile ‘zhangyf.vir56k:oknet:0.0.1‘

Example:

dependencies {    compile fileTree(dir: ‘libs‘, include: [‘*.jar‘])    compile ‘zhangyf.vir56k:oknet:0.0.1‘}
Some configuration at System boot time

For example, in your child class that inherits from application, or when the main activity is started.

        //配置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 simple request, and string type of 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, "==成功:" + result);                    alert("==成功");                }            }).excute();
Requests with parameters, and JSON-serialized callbacks
    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();
Custom handling exception code (message code not equal to 0 in messages 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, "= = success:" + result);                Alert ("= = Success"); } @Override public boolean onfailure (int httpcode, Exception ex, Commonmessage Responsemessa GE, String responsestring) {if (ex instanceof nozeroexception) {Nozeroexceptio                        n nozeroexception = (nozeroexception) ex;                        int code = Nozeroexception.getcode (); LOG.I (TAG, "!!!!!!!!                        Failure: "+ nozeroexception); Alert ("!!!!!!!!!!!!!!!!                        Failure, "+ nozeroexception); Return false;//If you do not need the default exception handler to process again, you can return true} return SUPER.ONFAIlure (Httpcode, ex, Responsemessage, responsestring); }}). Excute ();
Uploading files
  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", "50E2904CA4            93d5d25475e4e080858925 ")/************************ power in this line alone, the others are the same ***************************/ . File ("file", f)/************************ power is just in this line, and the others are the same ***************************/. O Nsuccess (New commoncallback<demo3bean> (demo3bean.class) {@Override public void ONSUCC ESS (demo3bean result, Commonmessage responsemessage, String responsestring) {log.i (TAG, "!!!                    Success: "+ Result.count); Alert ("!!                Success "+ Result.count); }}). Excute ();  
Handling situations where a progress bar needs to be displayed
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();
Send HTTP requests in a synchronous manner
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&L T String> (string.class) {@Override public void onsuccess (String result, Co                            Mmonmessage responsemessage, String responsestring) {isOK = true;                        MRESULT1 = result; } @Override public boolean onfailure (int httpcode, Exception Exception, Comm                            OnMessage 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, "= =                Work: "+ MRESULT1);            Alert ("= = Success"); }}}.execute ();}
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("文件下载进度, read %s/%s", bytesRead, contentLength));        }        @Override        protected void onSuccess(Call call, File file) {            System.out.println("文件下载成功吗 =" + file.exists());        }    });}

Android Development-Development framework using the OKHTTP framework package

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.