Android an improved Okhttp package library

Source: Internet
Author: User

Reprint please indicate the source:
http://blog.csdn.net/lmj623565791/article/details/49734867;
This article is from: "Zhang Hongyang's Blog"

I. Overview

Before writing an Android Okhttp completely parse is the time to understand the okhttp, in fact, mainly as okhttp of the popularity of the article, of course, there is also a simple package of tools, did not expect to pay attention to and use of a lot of people, because this enthusiasm, the tool class is also a surge in methods, Various heavy-duty methods, which are extremely inconvenient to use. Really ashamed.

So, over the weekend, take some time to disassemble and write the tool class. By the way intact function, as far as possible to enhance its ease of use and scalability.

The improvement of the title also refers to the improvement of my previous code.

Assuming you don't understand okhttp, it's time to get to know Okhttp through Android Okhttp.

Ok. So for now, the package repository supports:

    • A general GET request
    • General POST request
    • HTTP-based file upload
    • File download
    • Upload the download Progress callback
    • Loading pictures
    • Support for request callbacks. Directly returns objects, collections of objects
    • Support for session retention
    • Support Self-signed site HTTPS access, provide method settings under the certificate can be
    • Support Canceling a request

Source code Address: Https://github.com/hongyangAndroid/okhttp-utils

Introduced:

    • Android Studio

      Before use. For users of Android studio. can choose to join:

      project(‘:okhttputils‘)

      Or

      ‘com.zhy:okhttputils:2.0.0‘
    • Eclipse

      Copy the source code yourself.

Ii. Basic methods of use

The basic usage format for the moment is:

OkHttpUtils    .get()    .url(url)    .addParams("username""hyman")    .addParams("password""123")    .build()    .execute(callback);

Through the chain to join the various parameters according to their own needs, and finally call execute (callback) to run, the incoming callback is represented by asynchronous. Assume that simple execute () represents a synchronous method invocation.

Can see that the previous heap of get overloaded methods was canceled. The parameters can also be flexibly selected.

Here's a quick look at all the ways to use it:

(1) Get request
string url =  "HTTP +/ www.csdn.net/"; okhttputils. Get (). URL (URL). Addparams (" username ",  ). Addparams ( password ,     "123" ) . Build (). Execute (new  stringcallback () { @Override  public  void onerror  (Request request, Exception e) {} Span class= "hljs-annotation" > @Override  public  void  onresponse  (String response) {} });
(2) Post request
 OkHttpUtils    .post()    .url(url)    .addParams("username""hyman")    .addParams("password""123")    .build()    .execute(callback);
(3) Post String
OkHttpUtils    .postString()    .url(url)    .content(new Gson().toJson(new User("zhy""123")))    .build()    .execute(new MyStringCallback());   

The string is passed as a request body to the server, such as a JSON string.

(4) Post File
OkHttpUtils    .postFile()    .url(url)    .file(file)    .build()    .execute(new MyStringCallback());

The file is passed as the request body to the server.

(5) Post-based file upload (similar to a form on the web)
OkHttpUtils.post()//    .addFile("mFile""messenger_01.png", file)//    .addFile("mFile""test1.txt", file2)//    .url(url)    .params(params)//    .headers(headers)//    .build()//    .execute(new MyStringCallback());
(6) Download file
Okhttputils//. Get ()//. URL (URL)//. Build ()//. Execute (NewFilecallback (Environment.getexternalstoragedirectory (). GetAbsolutePath (),"Gson-2.2.1.jar")//{@Override         Public void inProgress(floatProgress) {mprogressbar.setprogress (int) ( -* progress)); }@Override         Public void OnError(Request request, Exception e) {LOG.E (TAG,"OnError:"+ e.getmessage ()); }@Override         Public void Onresponse(File file) {LOG.E (TAG,"Onresponse:"+ File.getabsolutepath ()); }    });
(7) Show pictures
OkHttpUtils    .get()//    .url(url)//    .build()//    .execute(new BitmapCallback()    {        @Override        publicvoidonError(Request request, Exception e)        {            mTv.setText("onError:" + e.getMessage());        }        @Override        publicvoidonResponse(Bitmap bitmap)        {            mImageView.setImageBitmap(bitmap);        }    });

Ha, see now. It's much clearer.

Third, for uploading the download callback
new Callback<?>(){    //...    @Override    publicvoidinProgress(float progress)    {       //use progress: 0 ~ 1    }}

For the incoming callback there is a inprogress method, you need to get the progress of the direct replication of the method can be.

Four, for their own initiative to resolve to the entity class

Now it removes the dependency of Gson and provides a way to define callback, allowing the user to parse the returned data on their own StringCallback . FileCallback, BitmapCallback respectively, to return a string. Download the file and load the image.

Assuming, of course, that you want to parse into an object, you can:

publicabstractclass UserCallback extends Callback<User>{    //非UI线程,支持不论什么耗时操作    @Override    publicparseNetworkResponsethrows IOException    {        String string = response.body().string();        new Gson().fromJson(string, User.class);        return user;    }}

Use your favorite JSON parsing library to complete.

Resolves List<User> to, for example, the following:

publicabstractclass ListUserCallback extends Callback<List<User>>{    @Override    publicList<User> parseNetworkResponse(Response response) throws IOException    {        String string = response.body().string();        ListnewList.class);        return user;    }}
Five, for HTTPS one-way authentication

Very easy, get the Xxx.cert certificate.

and then call

OkHttpUtils.getInstance()        .setCertificates(inputstream);

Recommended use, such as my certificate is placed in the Assets folder:

/** * Created by Zhy on 15/8/ */ public  class  myapplication  extends  application  {  @Override  public  void  oncreate  () {super . O        Ncreate ();        try  {okhttputils. getinstance (). Setcertificates (Getassets (). Open ( "aaa.c        ER "), Getassets (). Open (" Server.cer "));        } catch  (IOException e) {e.printstacktrace (); }    }}

We can. Don't forget to register the application.

Note: It is not necessary to assume that the HTTPS site is a certificate issued by an authoritative authority. A self-signed certificate is required.

Vi. configuration (1) Global configuration

Can be in the application. Pass:

OkHttpClient client = OkHttpUtils.getInstance().getOkHttpClient();

Then call the client's various set methods.

Like what:

client.setConnectTimeout(100000, TimeUnit.MILLISECONDS);
(2) Setting timeouts for individual requests

For example, there is a need to set read and write waiting time for files.

 OkHttpUtils    .get()//    .url(url)//    .tag(this)//    .build()//    .connTimeOut(20000)    .readTimeOut(20000)    .writeTimeOut(20000)    .execute()

After calling build (). A variety of timeout can be set immediately.

(3) cancel a single request
 RequestCall call = OkHttpUtils.get().url(url).build(); call.cancel();
(4) Cancellation request based on tag

For now, the last parameter is added to the supported method Object tag , and the cancellation is OkHttpUtils.cancelTag(tag) run.

For example: In activity, when the activity destroys the cancellation request:

OkHttpUtils    .get()//    .url(url)//    .tag(this)//    .build()//@OverrideprotectedvoidonDestroy(){    super.onDestroy();    //能够取消同一个tag的    OkHttpUtils.cancelTag(this);//取消以Activity.this作为tag的请求}

For example, all requests for the current Activity page are tagged with the activity object. Can be canceled in Ondestory.

Vii. Brief introduction of encapsulation

In fact the entire package process is relatively simple, here is a brief description of the okhttp a request for the process is basically this:

//Create Okhttpclient ObjectOkhttpclient mokhttpclient =NewOkhttpclient ();//Create a requestFinalRequest Request =NewRequest.builder (). URL ("Https://github.com/hongyangAndroid"). build ();//new CallCall call = Mokhttpclient.newcall (request);//Request Join ScheduleCall.enqueue (NewCallback () {@Override     Public void onfailure(Request request, IOException e) {    }@Override     Public void Onresponse(FinalResponse Response)throwsIOException {//string htmlstr = Response.body (). String ();}});

The basic difference, in fact, is the request construction process.

I abstracted a class for request:OkHttpRequest

 Public Abstract  class okhttprequest{    protectedRequestbody Requestbody;protectedRequest request;protectedString URL;protectedString tag;protectedMap<string, string> params;protectedMap<string, string> headers;protected okhttprequest(string URL, string tag, map<string, string> params, map<string, string> headers) { This. url = URL; This. tag = tag; This. params = params; This. headers = headers; }protected AbstractRequestbuildrequest();protected AbstractRequestbodyBuildrequestbody();protected void prepareinvoked(Resultcallback callback)        {requestbody = Buildrequestbody ();        Requestbody = Wraprequestbody (Requestbody, callback);    Request = Buildrequest (); }protectedRequestbodyWraprequestbody(Requestbody Requestbody,FinalResultcallback callback) {returnRequestbody; } Public void Invokeasyn(Resultcallback callback)        {prepareinvoked (callback);    Mokhttpclientmanager.execute (Request, callback); }//Other common methods}

A request for the construction, I divided into three steps: buildRequestBody , wrapRequestBody buildRequest This order, when the above three methods are not a problem, we got the request. Then you can run it.

But for different requests. The build process for requestbody and request is different. So you can see buildRequestBody that buildRequest for abstract methods, that is, different request classes. OkHttpGetRequestFor example, OkHttpPostRequest you need to build your own request.

For the wrapRequestBody method, you can see that it is basically a null implementation by default, mainly because not all of the request classes need to replicate it, just upload the time, need to callback progress. It is necessary to pack the requestbody. So this method is similar to a hook.

In fact, this process is somewhat similar to the template method pattern, and is interested to be able to look at a short introduction to design pattern Template method pattern Display Program Ape Day.

For a more specific use, you can view the readme above GitHub. and demo, the demo now includes:

For the two button that uploads the file, you need to build the server yourself. The other buttons can be tested directly.

Finally, because my level is limited. And time is more hasty ~ ~ To find the problem, welcome to mention issue, I will take time to solve. A Nice Day ~

Source code click to download

Welcome to follow my Weibo:
http://weibo.com/u/3165018720

Group No.: 514447580, welcome into the group

Public Number: Hongyangandroid
(Welcome attention, the first time to push the blog post information)

Android an improved Okhttp package library

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.