Android an improved Okhttp package library

Source: Internet
Author: User

I. Overview

Before writing an Android Okhttp full parsing is the time to understand the okhttp, in fact, mainly as a okhttp of the popularity of the article, of course, the inside is also a simple package of tools, did not expect to pay attention to and use of a lot of people, because of this enthusiasm, the tool class method is also a surge, various overloaded methods , so that it is very inconvenient to use, really ashamed.

So, in this weekend, take some time to the tool class, re-disassembly and writing, the way to improve the function, as far as possible to enhance its use of convenience and scalability.

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

If you don't understand okhttp, you can fully parse it by Android Okhttp it's time to get to know 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 Request callback, return object, object collection directly
    • Support for session retention
    • Support Self-signed web site HTTPS access, provide method settings under the certificate on the line
    • Support Canceling a request

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

Ii. Basic Usage

The current basic usage format is:

new OkHttpRequest.Builder()    .url(url)    .params(params)    .headers(headers)    .tag(tag)    .get(callback);

Through the builder to add a variety of parameters according to their own needs, and finally call get (callback) to execute, the incoming callback represents is asynchronous. If a simple get () represents a synchronous method call.

As you can see, the previous heap of get overloaded methods has been canceled, and the parameters can be flexibly selected.

Similarly, in addition to the Get method, there are post, upload, download, displayimage. Usage is basically the same. Here's a quick look.

(1) Get request
//最基本new OkHttpRequest.Builder()    .url(url)    .get(callback);//扩展new OkHttpRequest.Builder()    .url(url)    .params(params)    .headers(headers)    .tag(tag)    .get(callback);
(2) Post request
//最基本new OkHttpRequest.Builder()    .url(url)    .params(params)    .post(callback);//扩展new OkHttpRequest.Builder()    .url(url)    .params(params)    .headers(headers)    .tag(tag)    .post(callback);
(3) post-based file upload
//基本new OkHttpRequest.Builder()    .url(url)    .files(files)    .upload(callback);//扩展new OkHttpRequest.Builder()    .url(url)    .params(params)    .headers(headers)    .tag(tag)    .files(files)    .upload(callback);
(4) Download file
//基本new OkHttpRequest.Builder()    .url(url)    .destFileDir(destFileDir)    .destFileName(destFileName)    .download(callback);//扩展new OkHttpRequest.Builder()    .url(url)    .params(params)    .headers(headers)    .tag(tag)    .destFileDir(destFileDir)    .destFileName(destFileName)    .download(callback);
(5) Show pictures
//基本 new OkHttpRequest.Builder()    .url(url)    .imageview(imageView)    .displayImage(callback);//扩展new OkHttpRequest.Builder()    .url(url)    .params(params)    .headers(headers)    .tag(tag)    .imageview(imageView)    .errorResId(errorResId)    .displayImage(callback);

is automatically compressed according to the size of the ImageView.

Ha, at present, much clearer.

Third, for uploading the download callback
new ResultCallback<List<User>>(){    //...    @Override    public void inProgress(float progress) { //use progress: 0 ~ 1 }}

For incoming callback There is a inprogress method, when the upload (callback), download (callback) method is called, Progress callback 0~1. (UI thread).

Iv. for automatic parsing to entity classes
//对象new ResultCallback <User>(){    //...    @Override    public void onResponse(User user) { mTv.setText(user.username); }}//集合new ResultCallback<List<User>>(){ //... @Override public void onResponse(List<User> users) { mTv.setText(users.get(0).username); }}

Currently supports a single object, or collection, internally dependent on Gson completion.

Note: Generics must be set, if you do not need to convert to entity object, write new ResultCallback<String>(){} ,

Five, for HTTPS one-way authentication

Very simple, get Xxx.cert's certificate.

and then call

OkHttpClientManager.getInstance()        .getHttpsDelegate()       .setCertificates(inputstream);

Recommended ways to use, such as my certificates, are placed in the assets directory:

/** * Created by zhy on 15/8/25. */public class MyApplication extends Application{ @Override public void onCreate() { super.onCreate(); try { OkHttpClientManager.getInstance() .getHttpsDelegate() .setCertificates(getAssets().open("aaa.cer"), getAssets().open("server.cer")); } catch (IOException e) { e.printStackTrace(); } }}

Can. Don't forget to register for application.

Note: If the HTTPS Web site is a certificate issued by an authoritative authority, the above settings are not required. Self-signed certificates are only required.

Vi. 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 generally the case:

Create Okhttpclient object Okhttpclient mokhttpclient =New Okhttpclient ();Create a requestfinal Request request = new request.builder (). URL ( "https://github.com/hongyangAndroid"). Build (); //new callcall call = Mokhttpclient.newcall (request); //request join Schedule Call.enqueue (new Callback () {  @Override public void onfailure (Request request, IOException e) {}  @Override public void onresponse ( final Response Response) throws ioexception {//string htmlstr = Response.body (). String (); }});  

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

I abstracted a class for request:OkHttpRequest

PublicAbstractClassokhttprequest{protected Requestbody requestbody;protected request request;protected String URL;protected String tag;Protected map<string, string> params;Protected map<string, string> headers;ProtectedOkhttprequest (string url, string tag, map<string, string> params, map<string, string> headers) {This.url = URL;This.tag = tag;This.params = params;This.headers = headers; }ProtectedAbstract RequestBuildrequest ();protected abstract requestbody  Buildrequestbody (); protected void prepareInvoked ( Resultcallback callback) {requestbody = Buildrequestbody (); requestbody = Wraprequestbody (Requestbody, callback); Request = Buildrequest (); } protected requestbody wraprequestbody (RequestBody Requestbody, final Resultcallback callback) {return Requestbody; } public void invokeAsyn ( Resultcallback callback) {prepareinvoked (callback); Mokhttpclientmanager.execute (request, callback);} //Other common methods}           

A request is built, I have three steps:, in buildRequestBody wrapRequestBody buildRequest This order, when the above three methods are not a problem, we get the request, and then execute.

But for different requests, the Requestbody and request build process is different, so you can see buildRequestBody , for the buildRequest abstract method, that is, different request classes, such as OkHttpGetRequest , and OkHttpPostRequest so need to build their 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, only when uploading, need to callback progress, need to wrap the requestbody, so this method is similar to a hook.

In fact, this process is somewhat similar to the template method pattern, and it is interesting to look at a short introduction to the design pattern template method pattern to show the programmer's Day.

For more detailed usage, you can view the readme above GitHub as well as the demo, which currently includes:

For the two button to upload the file, you need to build a server, the other buttons can be directly tested.

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.