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

Introduced:

    • Android Studio

      Before using, for Android studio users, you can choose to add:

      project(‘:okhttputils‘)
      • 1

      Or

      ‘com.zhy:okhttputils:2.0.0‘
      • 1
    • Eclipse

      Copy the source code yourself.

Ii. Basic Usage

The current basic usage format is:

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

Through the chain to add various parameters according to their own needs, and finally call execute (callback) to execute, the incoming callback is to represent the asynchronous. If the simple execute () 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.

Here's a quick look at the whole usage:

(1) Get request
"http://www.csdn.net/";OkHttpUtils    .get()    .url(url)    .addParams("username", "hyman")    .addParams("password", "123") .build() .execute(new StringCallback() { @Override public void onError(Request request, Exception e) { } @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 request body is passed 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 (New Filecallback (Environment.getexternalstoragedirectory (). GetAbsolutePath (),"Gson-2.2.1.jar")//{ @Override public void inProgress (float progress) { Mprogressbar.setprogress ((int) (progress)); @Override public void OnError (Request request, Exception e) {log.e (TAG, "onError:" + E.getmessag E ()); } @Override public void onresponse (file file) {log.e (TAG, "onresponse:" + File.getabsolutepath ());
(7) Show pictures
OkHttpUtils    .get()//    .url(url)//    .build()//    .execute(new BitmapCallback()    {        @Override public void onError(Request request, Exception e) { mTv.setText("onError:" + e.getMessage()); } @Override public void onResponse(Bitmap bitmap) { mImageView.setImageBitmap(bitmap);

Ha, at present, much clearer.

Third, for uploading the download callback
new Callback<?>(){    //...    @Override    public void inProgress(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.

Iv. for automatic parsing to entity classes

Currently removes the dependency of Gson, provides a custom callback way to allow users to parse the returned data themselves, currently provided StringCallback , respectively, to FileCallback BitmapCallback return string, file download, load picture.

Of course, if you want to parse the object, you can:

public abstract class UserCallback extends Callback<User>{ //非UI线程,支持任何耗时操作 @Override public User parseNetworkResponse(Response response) throws IOException { String string = response.body().string(); User user = new Gson(www.2636666.cn).fromJson(string, User.class); return user;

You can use your favorite JSON parsing library to complete.

Parse into List<User> , then the following:

public abstract class ListUserCallback extends Callback<List<User>>{ @Override public List<User> parseNetworkResponse(Response response) throws IOException { String string = response.body().string(); List<User> user = new Gson().fromJson(string, List.class); return user;
Five, for HTTPS one-way authentication

Very simple, get Xxx.cert's certificate.

and then call

OkHttpUtils.getInstance()        .setCertificates(inputstream);
    • 1
    • 2
    • 3

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(www.mhylpt.com) { super.onCreate(); try { OkHttpUtils .getInstance() .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. configuration (1) Global configuration

In application, you can pass:

OkHttpClient client = OkHttpUtils.getInstance(www.365soke.cn ).getOkHttpClient(www.senta77.com);
    • 1
    • 2

Then call the client's various set methods.

For example:

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

For example, the need for files to set read and write wait time a little more.

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

After you call build (), you can set up various timeout types immediately.

(3) cancel a single request
 RequestCall call = OkHttpUtils.get().url(url).build(); call.cancel();
    • 1
    • 2
    • 3
(4) Cancel request according to tag

Currently, the last parameter is added to the supported method Object tag , and cancellation is OkHttpUtils.cancelTag(tag) performed by execution.

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

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

For example, the current Activity page all requests with the activity object as tag, can be unified in the ondestory cancellation.

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

Create Okhttpclient object Okhttpclient mokhttpclient =New Okhttpclient (www.wanmeiyuele.cn);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 ( www.taohuayuan178.com/). 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 method 

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.

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

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.