Android okhttp Full parsing It's time to get to know okhttp.

Source: Internet
Author: User
Tags http file upload http post

Reprinted from:

Android okhttp Full parsing It's time to get to know okhttp.

I. Overview

Recently in the group heard a variety of discussion okhttp topic, it can be seen okhttp reputation is quite good. Plus Google seems to have deleted the HttpClient API in version 6.0, not to comment on this behavior. In order to better in response to network access, learning under Okhttp is still quite necessary, this blog first introduces the simple use of okhttp, mainly includes:

A general GET request
General POST request
HTTP-based file upload
File download
Loading pictures
Support Request callback, return object, object collection directly
Support for session retention
Finally, the above features will be encapsulated, complete package class address see: Https://github.com/hongyangAndroid/okhttp-utils

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

Compile ' com.squareup.okhttp:okhttp:2.4.0 '

Second, the use of the tutorial

(i) Http Get

For the Network Load library, the most common must be HTTP GET requests, such as getting the content of a Web page.

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 (); } });  
    1. The above is to send a GET request step, first constructs a request object, the parameter at least has a URL, of course you can set more parameters such as: header, method and so on Request.builder.

    2. The request object is then constructed to get a call object, similar to encapsulating your requests as tasks, and since it is a task, there are methods such as execute () and cancel ().

    3. Finally, we want to execute the request asynchronously, so we're calling Call.enqueue, adding call to the dispatch queue, and waiting for the task to finish, we can get the result in callback.

See this, you will find that the overall writing is still relatively long, so the package must be done, or each request so write, exhausted.

OK, there are several points to note:

    • The parameters of the Onresponse callback are response, and generally, for example, we want to get the returned string, which can be obtained through the Response.body (). String (), or if you want to get the returned binary byte array, call Response.body (). bytes (); If you want to get the returned InputStream, call Response.body (). ByteStream ().

See this, you may be surprised, unexpectedly still can get the return of InputStream, see this at least can realize a little, here support big file download, have InputStream we can write the file by IO way. However, it also shows that the thread that this onresponse executes is not the UI thread. Yes, if you want to manipulate the controls, you need to use handler and so on, for example:

@Overridepublic void onResponse(final Response response) throws IOException{ final String res = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { mTv.setText(res); } });}
    • We're doing this asynchronously, and of course it supports blocking, and we've also said that call has an execute () method.

(ii) Http Post carrying parameters

It seems that the above simple get request, basically the entire usage also mastered, such as the post carrying parameters, is only the request of the construction of the difference.

Request request = buildMultipartFormRequest(        new File[]{file}, new String[]{fileKey}, null);FormEncodingBuilder builder = new FormEncodingBuilder(); builder.add("username","张鸿洋");Request request = new Request.Builder() .url(url) .post(builder.build()) .build(); mOkHttpClient.newCall(request).enqueue(new Callback(){}); 

As we all know, the parameters are contained in the request body when post, so we pass the Formencodingbuilder. Add multiple string key-value pairs, then construct the Requestbody, and finally complete the construction of our request.

The back is the same as above.

(iii) HTTP-based file upload

Next we are introducing a builder that can construct requestbody, called Multipartbuilder. When we need to do something like a form upload, we can use it to construct our requestbody.

File File =New File (Environment.getexternalstoragedirectory (),"Balabala.mp4"); Requestbody filebody = requestbody.create (Mediatype.parse ("Application/octet-stream"), file); Requestbody Requestbody =new multipartbuilder (). Type (Multipartbuilder.form). Addpart (Headers.of (null, " 张鸿洋 ")). Addpart (Headers. Of ( "Content-disposition", new request.builder (). URL (new Callback () {//...}"             

The code above passes a key-value pair Username: Zhang Hongyang and a file to the server. We can add key-value pairs or files by Multipartbuilder's Addpart method.

In fact, similar to the way we splicing analog browser behavior, if you do not understand this piece, you can refer to: from the principle point of view of the Android (Java) HTTP file upload

OK, for our first directory also left pieces of download, file download, these two are through the callback response get byte[] and then decode into a picture; file download, is to get InputStream do write file operations, we do not repeat here.

For usage, you can also refer to the Bubble net okhttp use tutorial

Next we look at how to encapsulate the above code.

Three, Package
Because following the code above, writing multiple requests definitely contains a lot of duplicate code, so I want the encapsulated code call to be like this:

(i) Use

1. General GET requests:

 OkHttpClientManager.getAsyn("https://www.baidu.com", new OkHttpClientManager.ResultCallback<String>()        {            @Override            public void onError(Request request, Exception e) { e.printStackTrace(); } @Override public void onResponse(String u) { mTv.setText(u);//注意这里是UI线程 } }); 

For the general request, we want to give a URL, and then callback inside the direct manipulation of the control.

2. File upload and Carry parameters

We want to provide a way to pass in the Url,params,file,callback.

Okhttpclientmanager.postasyn ("Http://192.168.1.103:8080/okHttpServer/fileUpload",//New Okhttpclientmanager.resultcallback<string> () {@Overridepublic void onError @Override public void onresponse (String result) {}},//file,// "Mfile", //new okhttpclientmanager.param[]{ new okhttpclientmanager.param ( "username",  "Zhy"), new Okhttpclientmanager.param (  "password",  "123")});  

Key value pairs Nothing to say, the parameter 3 is file, parameter 4 is the name of the file, this name is not the name of the document;
That corresponds to the HTTP

<input type="file" name="mFile" >

Corresponds to the value after name, which is mfile.

3. File download

For file download, provide URL, target Dir,callback can.

OkHttpClientManager.downloadAsyn(    "http://192.168.1.103:8080/okHttpServer/files/messenger_01.png",        Environment.getExternalStorageDirectory().getAbsolutePath(), new OkHttpClientManager.ResultCallback<String>()    {        @Override        public void onError(Request request, IOException e) { } @Override public void onResponse(String response) { //文件下载成功,这里回调的reponse为文件的absolutePath }});

4. Display pictures

Display pictures, we want to provide a URL and a imageview, if the download is successful, directly to help us set up.

"http://images.csdn.net/20150817/1.jpg"); 

The interior automatically compresses the image automatically based on the size of the ImageView. Although this may not be a good place to load a large number of images at once, it is still available for the occasional loading of several images in the app.

Iv. Integration of Gson

Many people suggest that when used in the project, the server returns the JSON string, hoping that the client callback can get the object directly, so the integration into the Gson, perfect this function.

(i) Direct callback object

For example, there is now a user entity class:

Package com.zhy.utils.http.okhttp;PublicClassUser {Public String username;public String password;Publicuser () {//TODO auto-generated Constructor stub} public User< Span class= "Hljs-params" > (string username, string password) {this.username = Username; Span class= "Hljs-keyword" >this.password = password; }  @Override public String Span class= "Hljs-title" >tostring () {return " user{"+ " username= "" + Username +  "\" +   

Service side return:

{"username":"zhy","password":"123"}

The client can be called as follows:

 OkHttpClientManager.getAsyn("http://192.168.56.1:8080/okHttpServer/user!getUser",    new OkHttpClientManager.ResultCallback<User>(){    @Override    public void onError(Request request, Exception e) { e.printStackTrace(); } @Override public void onResponse(User user) { mTv.setText(u.toString());//UI线程 }});

We pass in the generic user and directly callback the user object inside the onresponse.
It is particularly important to note that if an error occurs during a JSON string---entity object, the program does not crash and the OnError method is called back.

Note: Here is a little update, the interface name is modified from Stringcallback to Resultcallback. The OnFailure method in the interface is modified to onerror.

(ii) Callback object collection

is still the user class above, the server returns

[{"username":"zhy","password":"123"},{"username":"lmj","password":"12345"}]

The client can invoke the following:

 OkHttpClientManager.getAsyn("http://192.168.56.1:8080/okHttpServer/user!getUser",new OkHttpClientManager.ResultCallback<User>(){    @Override    public void onError(Request request, Exception e) { e.printStackTrace(); } @Override public void onResponse(User user) { mTv.setText(u.toString());//UI线程 }});

We pass in the generic user and directly callback the user object inside the onresponse.
It is particularly important to note that if an error occurs during a JSON string---entity object, the program does not crash and the OnError method is called back.

Note: Here is a little update, the interface name is modified from Stringcallback to Resultcallback. The OnFailure method in the interface is modified to onerror.

(ii) Callback object collection

is still the user class above, the server returns

[{"username":"zhy","password":"123"},{"username":"lmj","password":"12345"}]

The client can invoke the following:

Select AllCopyput it in your notes .
  Okhttpclientmanager.getasyn (new okhttpclientmanager.resultcallback<list<user >> () { @Override  Public void onerror (Request request , Exception e) {e.printstacktrace ();}  @Override public void onresponse (list<user> us) {LOG.E ( Span class= "hljs-string" > "TAG", us.size () + 1). toString ());}});         

The only difference is that generics become list<user>, OK, if you find a bug or have any comments welcome message.

(turn) Android okhttp full parsing It's time to get to know okhttp.

Related Article

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.