An Improved okHttp encapsulation library for Android, androidokhttp
Worship ~
Reprinted please indicate the source:
Http://blog.csdn.net/lmj623565791/article/details/49734867;
This article is from: [Zhang Hongyang's blog]
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:
- Common get requests
- GENERAL post requests
- Http-based File Upload
- File Download
- Upload and download progress callback
- Attach Images
- Supports request callback to directly return objects and object sets
- Support session persistence
- Supports https access to a self-Signed website. You can set the certificate by using the method.
- Cancels a request.
Source Code address: https://github.com/hongyangAndroid/okhttp-utils
Introduction: compile 'com. squareup. okhttp3: okhttp: 3.3.1'
Ii. Basic usage
The basic usage format is as follows:
OkHttpUtils .get() .url(url) .addParams("username", "hyman") .addParams("password", "123") .build() .execute(callback);
You can use a chain to add various parameters based on your needs, and call execute (callback) for execution. Passing in callback indicates that it is asynchronous. Execute () indicates the synchronous method call.
As you can see, the previous get overload methods are removed, and the parameters can be flexibly selected.
Next, let's take a look at all the usage:
(1) GET request
String url = "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());
Input string to the server as the request body, for example, a json string.
(4) Post File
OkHttpUtils .postFile() .url(url) .file(file) .build() .execute(new MyStringCallback());
Pass the file as the request body to the server.
(5) POST-based file upload (similar to web forms)
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 an object
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) (100 * 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) display images
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); } });
Now, it's much clearer.
Iii. Upload/download callback
new Callback<?>(){ //... @Override public void inProgress(float progress) { //use progress: 0 ~ 1 }}
There is an inProgress method for the incoming callback. You need to obtain the progress and rewrite the method directly.
4. automatically resolved to an object class
In addition to Gson dependencies, the custom Callback method is provided to allow the user to parse the returned data.StringCallback
,FileCallback
,BitmapCallback
Returns the string, downloads the object, and loads the image.
Of course, if you want to parse it as an object, you can:
Public abstract class UserCallback extends Callback <User >{// non-UI thread, supports any time-consuming operation @ Override public User parseNetworkResponse (Response response) throws IOException {String string = response. body (). string (); User user = new Gson (). fromJson (string, User. class); return user ;}}
You can use your favorite Json Parsing Library.
ResolvedList<User>
, As follows:
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; }}
5. One-way https Authentication
It is very easy to get the xxx. cert certificate.
Then call
OkHttpUtils.getInstance() .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 { OkHttpUtils .getInstance() .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.
Vi. configuration (1) Global Configuration
You can run the following command in Application:
OkHttpClient client = OkHttpUtils.getInstance().getOkHttpClient();
Then call various set methods of the client.
For example:
client.setConnectTimeout(100000, TimeUnit.MILLISECONDS);
(2) set timeout for a single request
For example, you need to set a read/write wait time for files.
OkHttpUtils .get()// .url(url)// .tag(this)// .build()// .connTimeOut(20000) .readTimeOut(20000) .writeTimeOut(20000) .execute()
After you call build (), you can set various timeouts.
(3) cancel a single request
RequestCall call = OkHttpUtils.get().url(url).build(); call.cancel();
(4) cancel the request according to the tag
Currently, the last parameter is added to all supported methods.Object tag
.OkHttpUtils.cancelTag(tag)
Run.
For example, in an Activity, when the Activity destroys the cancellation request:
OkHttpUtils. get ()//. url (url )//. tag (this )//. build () // @ Overrideprotected void onDestroy () {super. onDestroy (); // you can cancel the OkHttpUtils of the same tag. cancelTag (this); // cancel with Activity. this is a tag request}
For example, all requests on the current Activity page use Activity objects as tags and can be canceled in onDestory.
VII. 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<String, String> params; protected Map<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 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 ~