Open Source project okhttpplus--support Get, POST, UI thread callback, JSON format parsing, chained invocation, file upload download

Source: Internet
Author: User
Tags getmessage throwable

Okhttpplus Introduction

Project Address: Https://github.com/ZhaoKaiQiang/OkHttpPlus

Main Features: Okhttp package, support Get, POST, UI thread callback, JSON format parsing, chain call, small file upload download and progress monitoring and other functions

Why write a library like this?

First of all, because Okhttp has been implemented as the underlying HTTP after 4.4, the Okhttp library is very powerful and worth learning.

Second, in my opinion, okhttp use is not as convenient as volley, okhttp callbacks are in the worker thread, so if you operate the view in the callback, you need to switch to the UI thread, very cumbersome, so need to encapsulate. There is also the use of okhttp as the volley underlying HTTP implementation, the sending request, the maintenance request queue is volley, the actual HTTP request is okhttp.

About volley and Ookhttp combined demo-Poke Fried Egg project

How to use initialization

You can complete the initialization in the application, because the Okhttp encapsulation is mainly used in the proxy design mode, using OkHttpProxy.getInstance() can be obtained to the singleton client, you can set arbitrary parameters as before without encapsulation, such as setting the timeout time and ignoring HTTPS authentication.

 Public  class okapplication extends application {    @Override     Public void onCreate() {Super. OnCreate ();        Okhttpclient okhttpclient = Okhttpproxy.getinstance (); Okhttpclient.setconnecttimeout (Ten, timeunit.seconds); Okhttpclient.setreadtimeout ( the, timeunit.seconds); Okhttpclient.setwritetimeout ( the, timeunit.seconds);//ignore HTTPS AuthenticationOkhttpclient.sethostnameverifier (NewMyhostnameverifier ());Try{Sslcontext sc = sslcontext.getinstance ("TLS"); Sc.init (NULL,Newtrustmanager[]{NewMytrustmanager ()},NewSecureRandom ());        Okhttpclient.setsslsocketfactory (Sc.getsocketfactory ()); }Catch(NoSuchAlgorithmException e)        {E.printstacktrace (); }Catch(Keymanagementexception e)        {E.printstacktrace (); }    }}
Get method

Most of the cases you are dealing with Okhttpproxy this proxy class, and okhttpplus support chained calls, built-in builder design patterns, so you can use

 Okhttpproxy.get (). URL (url_user). Tag (t His ). Execute (new  okcallback<user> (new  okjsonparser<user> () {}) { @Override  public  void  onsuccess  (int  code, user user) {Tv_response.sette XT (User.tostring ()); }  @Override  public  void  onfailure  (Throwable e) { Tv_response.settext (E.getmessage ()); } });

In order to support the return value resolution, I use generics here, in the Okcallback constructor, you need to pass in a parser, okhttpplus internal support 5 kinds of parsers, which can solve most of your needs

    • Okbaseparser, base class for all parsers, cannot be used directly
    • Okbasejsonparser, the base class for all JSON parsers, you can inherit it to define your own JSON parsing
    • Okjsonparser,json parser, supports parsing of Jsonobject and Jsonarray, using Gson as parser by default
    • Oktextparser,string parser that supports the output of the result in string mode
    • Okfileparser, file parser, support to save the results as a file, you can use to download files, but do not support large file download

So if you want to get a jsonarray, you can do it like this

Okhttpproxy.get (). URL (url_user). Tag ( This). Execute (NewOkcallback<list<user>> (NewOkjsonparser<list<user>> () {}) {@Override                     Public void onsuccess(intCode, list<user> users) {Tv_response.settext (users.tostring ()); }@Override                     Public void onfailure(Throwable e)                    {Tv_response.settext (E.getmessage ()); }                });

If you want to get string data, you can

 Okhttpproxy.get (). URL (url_baidu). Tag ( Span class= "Hljs-keyword" >this ). Execute (new  okcallback<string& gt; (new  oktextparser ()) { @Override  public  void  onsuccess  (int  code, String s) {Tv_response.settext (                    s); }  @Override  public
       void  onfailure  (Throwable e) {                    Tv_response.settext (E.getmessage ()); }                });

Of course, if you want to customize a parser, it's perfectly possible.

The parser section of Okhttpplus uses the policy design pattern, so you can customize a parsing strategy as follows to complete the parsing of the results

Public class jokeparser<t> extends okjsonparser<t> {    @Nullable    @OverridePublic T Parse (Response Response)throwsIOException {String jsonstr = Response.body (). String ();Try{jsonstr =NewJsonobject (JSONSTR). Getjsonarray ("Comments"). ToString ();returnMgson.fromjson (JSONSTR,NewTypetoken<arraylist<joke>> () {}.gettype ()); }Catch(Jsonexception e) {E.printstacktrace ();return NULL; }    }}

You can then parse the return result into ArrayList.

  OkHttpProxy.get()                .url(Joke.getRequestUrl(1))                .tag(this).execute(new OkCallback<List<Joke>>(new JokeParser()) {            @Override            publicvoidonSuccess(int code, List<Joke> jokes) {                tv_response.setText(jokes.toString());            }            @Override            publicvoidonFailure(Throwable e) {                tv_response.setText(e.getMessage());            }        });
Post method

The Post method is similar to the Get method, and you can send the POST request as follows and add the header and params.

Okhttpproxy. Post (). URL (url_users). Tag ( This). Addparams ("Name","Zhaokaiqiang"). AddHeader ("Header","Okhttp"). Execute (NewOkcallback<arraylist<user>> (NewOkjsonparser<arraylist<user>> () {}) {@Override                     Public void onsuccess(intCode, arraylist<user> users) {Tv_response.settext (users.tostring ()); }@Override                     Public void onfailure(Throwable e)                    {Tv_response.settext (E.getmessage ()); }                });

You may have noticed that I called the tag () method when sending each request, so you can cancel the request when it is not needed.

@Override    protectedvoidonDestroy() {        super.onDestroy();        OkHttpProxy.cancel(this);    }
Download

You can download a file as follows, but because the content is in memory, it does not support large file downloads, or Oom

String Desfiledir = Environment.getexternalstoragedirectory (). GetAbsolutePath (); Okhttpproxy.download (Url_dowmload,NewDownloadlistener (Desfiledir,"Json.jar") {@Override             Public void onuiprogress(Progress Progress) {//When the download resource length is not known, progress.gettotalbytes () is-1, the download progress cannot be displayed at this time                intPro = (int) (Progress.getcurrentbytes ()/progress.gettotalbytes () * -);if(Pro >0) {pb.setprogress (pro); } KLOG.D ("Pro ="+ Pro +"getcurrentbytes ="+ progress.getcurrentbytes () +"gettotalbytes ="+ progress.gettotalbytes ()); }@Override             Public void onsuccess(File file)            {Tv_response.settext (File.getabsolutepath ()); }@Override             Public void onfailure(Exception e)            {Tv_response.settext (E.getmessage ());    }        }); }
Upload

Okhttpplus also support small file upload, I am here to test the use of seven cattle upload api,token is a deadline, so you need to build your own test at the following URL

 /** * Use seven KN upload interface, token is valid for 12 hours, if token is invalid, please obtain * token generated URL below http://jsfiddle.net/gh/get/extjs/4.2/icattlecoder/j Sfiddle/tree/master/uptoken * <p/> * AK = Iuy4jnozhp6o-rx9qsglf9jmtakfrkl07gnssida * CK = dkfa7gptny1k4h WNQYNRA3QAZHRZP-WMSS15VUB6 * bucke_name = Zhaokaiqiang * *     Public void UploadFile(View view) {File File =NewFile (Environment.getexternalstoragedirectory (),"Jiandan02.jpg");if(!file.exists ()) {Toast.maketext (mainactivity). This,"file does not exist, please modify the file path", Toast.length_short). Show ();return; } map<string, string> param =NewHashmap<> (); Param.put ("token", TOKEN); pair<string, file> pair =NewPair ("File", file); Okhttpproxy. Upload (). URL (url_upload). File (pair). SetParams ( param). Setwritetimeout ( -). Start (NewUploadlistener () {@Override                     Public void onsuccess(Response Response) {Tv_response.settext ("issuccessful ="+ response.issuccessful () +"\ n"+"code ="+ Response.code ()); }@Override                     Public void onfailure(Exception e)                    {Tv_response.settext (E.getmessage ()); }@Override                     Public void onuiprogress(Progress Progress) {intPro = (int) ((Progress.getcurrentbytes () +0.0)/progress.gettotalbytes () * -);if(Pro >0) {pb.setprogress (pro); } KLOG.D ("Pro ="+ Pro +"getcurrentbytes ="+ progress.getcurrentbytes () +"gettotalbytes ="+ progress.gettotalbytes ());    }                }); }
Source of Inspiration

Inspiration for this project and part of the code from the following two open source projects, thank them for sharing the spirit

    • Okhttp-utils
    • Coreprogress

Respect the original, reproduced please specify: from Kaizico (http://blog.csdn.net/zhaokaiqiang1992) infringement must investigate!

Follow my Weibo to get more content

Open Source project okhttpplus--support Get, POST, UI thread callback, JSON format parsing, chained invocation, file upload download

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.