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 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‘)
Or
‘com.zhy:okhttputils:2.0.0‘
-
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
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, at present, 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.
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:
publicabstractclass UserCallback extends Callback<User>{ //非UI线程,支持任何耗时操作 @Override publicparseNetworkResponsethrows IOException { String string = response.body().string(); new Gson().fromJson(string, User.class); return user; }}
You can use your favorite JSON parsing library to complete.
Parse into List<User> , then 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 simple, get Xxx.cert's certificate.
and then call
OkHttpUtils.getInstance() .setCertificates(inputstream);
Recommended ways to use, such as my certificates, are placed in the assets directory:
/** * 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 (); } }}
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().getOkHttpClient();
Then call the client's various set methods.
For example:
client.setConnectTimeout(100000, TimeUnit.MILLISECONDS);
(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();
(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()//@OverrideprotectedvoidonDestroy(){ 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 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 main 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 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 ~
SOURCE 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