An Improved okHttp encapsulation library for Android
I. Overview
I wrote an article about complete parsing of Android OkHttp. It is time to understand OkHttp. In fact, it is mainly used as a popular article on okhttp. Of course, it also encapsulates the tool class, I did not expect many people to pay attention to and use the tool. Due to this enthusiasm, the methods in the tool class also increased dramatically, and various heavy-load methods made it very inconvenient to use.
So this weekend, I took some time to re-disassemble and compile the tool class. By the way, I improved the function to improve its convenience and scalability as much as possible.
The title improvement also refers to the improvement of my previous code.
If you do not know okhttp, you can use Android OkHttp for full parsing.
OK. Currently, this encapsulated Library supports:
General get requests GENERAL post requests Http-based File Upload File Download upload download progress callback loading pictures support request callback, directly returning objects and object sets supports session persistence and https access to self-Signed websites. You can set the certificate to cancel a request.
Source Code address: https://github.com/hongyangAndroid/okhttp-utils
Introduction:
Android Studio
Before use, users of Android Studio can choose to add:
compile project(':okhttputils')
In the main project, you do not need to reference the okhttp dependency or import the Gson lib.
Eclipse
Download okhttputils. jar, add to project libs, and download okhttp. jar and gson-2.2.1.jar
Ii. Basic usage
The basic usage format is as follows:
new OkHttpRequest.Builder() .url(url) .params(params) .headers(headers) .tag(tag) .get(callback);
Use Builder to add various parameters as needed, and call get (callback) for execution. Passing in callback indicates that it is asynchronous. If the get () method is used, the synchronous method is called.
As you can see, the previous get overload methods are removed, and the parameters can be flexibly selected.
Similarly, in addition to the get method, there are also post, upload, download, and displayImage. The usage is basically the same. Let's take a brief look.
(1) GET request
// The most basic new OkHttpRequest. builder (). url (url ). get (callback); // extend new OkHttpRequest. builder (). url (url ). params (params ). headers (headers ). tag (tag ). get (callback );
(2) POST request
// The most basic new OkHttpRequest. builder (). url (url ). params (params ). post (callback); // extend new OkHttpRequest. builder (). url (url ). params (params ). headers (headers ). tag (tag ). post (callback );
(3) POST-based File Upload
// Basic new OkHttpRequest. builder (). url (url ). files (files ). upload (callback); // extended new OkHttpRequest. builder (). url (url ). params (params ). headers (headers ). tag (tag ). files (files ). upload (callback );
(4) download an object
// Basic new OkHttpRequest. builder (). url (url ). destFileDir (destFileDir ). destFileName (destFileName ). download (callback); // extend new OkHttpRequest. builder (). url (url ). params (params ). headers (headers ). tag (tag ). destFileDir (destFileDir ). destFileName (destFileName ). download (callback );
(5) display images
// Basic new OkHttpRequest. builder (). url (url ). imageview (imageView ). displayImage (callback); // extended new OkHttpRequest. builder (). url (url ). params (params ). headers (headers ). tag (tag ). imageview (imageView ). errorResId (errorResId ). displayImage (callback );
The image is automatically compressed based on the size of the ImageView.
Now, it's much clearer.
Iii. Upload/download callback
new ResultCallback
>(){ //... @Override public void inProgress(float progress) { //use progress: 0 ~ 1 }}
There is an inProgress method for the incoming callback. When the upload (callback) and download (callback) methods are called, the progress callback is 0 ~ 1. (UI thread ).
4. automatically resolved to an object class
// Object new ResultCallback
() {//... @ Override public void onResponse (User user) {mTv. setText (user. username) ;}// set new ResultCallback
> () {//... @ Override public void onResponse (List
Users) {mTv. setText (users. get (0). username );}}
Currently, a single object or set is supported, and the internal dependency is Gson.
Note: You must set the wildcard. If you do not need to convert it to an object, writenew ResultCallback (){}
,
5. One-way https Authentication
It is very easy to get the xxx. cert certificate.
Then call
OkHttpClientManager.getInstance() .getHttpsDelegate() .setCertificates(inputstream);
We recommend that you use this method. For example, place my certificate 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(); } }}
You can. Do not forget to register the Application.
Note: If the https website is a certificate issued by an authority, the preceding settings are not required. A self-signed certificate is required.
6. Encapsulation
In fact, the entire encapsulation process is relatively simple. Here we briefly describe the process for a okhttp request as follows:
// Create an 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); // Add the request to the scheduling 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 is actually the request construction process.
I abstracted a class for the Request:OkHttpRequest
public abstract class OkHttpRequest{ protected RequestBody requestBody; protected Request request; protected String url; protected String tag; protected Map
params; protected Map
headers; protected OkHttpRequest(String url, String tag, Map
params, Map
headers) { this.url = url; this.tag = tag; this.params = params; this.headers = headers; } protected abstract Request buildRequest(); 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 }
The construction of a request is divided into three steps:buildRequestBody
,wrapRequestBody
,buildRequest
In this order, when there are no problems with the above three methods, we get the request and then execute it.
However, for different requests, the construction process of requestBody and request is different, so we can see thatbuildRequestBody
,buildRequest
Abstract methods, that is, different request classes, suchOkHttpGetRequest
,OkHttpPostRequest
You need to build your own request.
ForwrapRequestBody
You can see that it is basically a blank implementation by default, mainly because not all request classes need to re-write it. Only when uploading is required, you need to call back the progress and wrap the requestBody, therefore, this method is similar to a hook.
In fact, this process is a bit similar to the template method mode. If you are interested, you can take a look at a short story about the design mode template method mode to show the programmer's day.
For more detailed usage, you can view the readme and demo on github. The current demo includes:
For the two buttons for uploading files, you need to build your own server. Other buttons can be directly tested.
Finally, due to my limited level and relatively short time ~~ If you find any problem, please refer to issue. I will take the time to solve it. Have a nice day ~