Android-async-http asynchttpclient Introduction

Source: Internet
Author: User

A while ago just moved home, plus the company to send a new version, so has been relatively busy, the article is not updated for several weeks. I don't have time for this weekend, just hanging out in the week.

Discover this great third-party open source class library that sends HTTP requests for Android development.

In Android development, it's so common to send and process HTTP requests that our code is littered with httpclient and the associated, smelly, long code.

They exist in every corner of your code, and each time you see it is disgusting, and you just want the server to return a string or JSON to you. Every time when I wrote it myself

Code, I would like to be able to simplify the process, perhaps 2, 3 lines of code can be done. Because for the simplest case, I only need to provide the request URL, the success of the

Callback and/or failed callback, that's all. For this type of problem (demand), it can be said that Android-async-http provides a nearly perfect solution.

By using it, you can greatly simplify your code, and your code will look more elegant.

I was attracted when I first saw it, especially the Async keyword, which is what our line of work knows, which is asynchronous execution, which means that its network requests are automatically in non-UI

Thread, you do not need any extra action (such as manually new one thread, etc.). The official website of the project:

http://loopj.com/android-async-http/, corresponding GitHub address: https://github.com/loopj/android-async-http

Here's a brief introduction: It's an asynchronous callback-based HTTP client built specifically for Android on the httpclient basis of Apache. All the Requests

Occurs entirely outside the UI thread, and callback occurs in the thread that created it, and the handler sending message mechanism is applied to Android. You can also apply asynchttpclient to the

In a service or a background thread, the library code automatically identifies the context in which it runs. Its feature include:

1. Send an asynchronous HTTP request to process the response in an anonymous callback object;

2. HTTP requests occur outside the UI thread;

3. Internal use of thread pool to handle concurrent requests;

4. Get/post parameters are constructed through the Requestparams class.

5. Built-in multipart file upload, do not need third-party library support;

6. Streaming JSON upload, no need for additional libraries;

7. Able to handle circular and relative redirects;

8. Size is small compared to your app, and all it has is 90kb;

9. Automatic Intelligent request retry mechanism in a variety of mobile connection environment;

10. Automatic gzip response decoding;

11. Built-in various forms of response parsing, there are native byte stream, String,json object, even can write response to the file;

12. Persistent cookie preservation, internal implementation using Android Sharedpreferences;

13. BaseJsonHttpResponseHandler和 integration through various JSON libraries;

14. Support SAX parser;

15. Support for various languages and content encoding, not just UTF-8.

Probably translated, these are only a general overview, the details of the use of the process to slowly feel, learning.

Next, take a look at the application of Android-async-http to write the code what it looks like. In simple terms, you only need 3 steps,

1. Create a asynchttpclient;

2. (optional) Set the request parameters through the Requestparams object;

3. Call a Get method of asynchttpclient to pass the callback interface implementation that you need (success and failure), usually anonymous inner class

, realize the Asynchttpresponsehandler, the class library itself also provides a lot of ready-made response handler, you generally do not need to create a.

To see how the code is written:

Asynchttpclient client =Newasynchttpclient (); Client.get ("Http://www.google.com",NewAsynchttpresponsehandler () {@Override Public voidOnStart () {//called before request is started} @Override Public voidOnsuccess (intStatusCode, header[] headers,byte[] response) {        //called when response HTTP status is " OK"} @Override Public voidOnFailure (intStatusCode, header[] headers,byte[] errorresponse, Throwable e) {        //called when response HTTP status is "4XX" (eg. 401, 403, 404)} @Override Public voidOnretry (intRetryno) {        //called when request is retried    }});

is not very concise, have not been shocked to? Anyway, my first time I saw a kind of brief encounter feeling, this is the way I think of the night! Here you just have to pass

Anonymous inner classes are implemented Asynchttpresponsehandler, and what's even better is that you only need to override the methods of interest, such as onsuccess and OnFailure in general.

This version of the Get method does not pass any parameters for the request, and of course you can pass various parameters via Requestparams, as follows:

Asynchttpclient client =Newasynchttpclient (); Requestparams params=Newrequestparams ();p arams.put ("Key", "value");p Arams.put ("More", "Data"); Client.get ("Http://www.google.com", params,NewAsynchttpresponsehandler () {@Override Public voidOnsuccess (intStatusCode, header[] headers,byte[] response) {SYSTEM.OUT.PRINTLN (response); } @Override Public voidOnFailure (intStatusCode, header[] headers,byte[] responsebody, throwable error) {LOG.D ("ERROR", error); }        });

The above example is that the return response is directly the case of the original word throttling, if you need to treat the returned result as a string, you only need to implement an anonymous

Texthttpresponsehandler, which inherits from Asynchttpresponse and converts the native byte stream into a string object based on the specified encoding,

The code is as follows:

Asynchttpclient client =Newasynchttpclient (); Requestparams params=Newrequestparams ();p arams.put ("Key", "value");p Arams.put ("More", "Data"); Client.get ("Http://www.google.com", params,NewTexthttpresponsehandler () {@Override Public voidOnsuccess (intStatusCode, header[] headers, String response) {System.out.println (response); } @Override Public voidOnFailure (intStatusCode, header[] headers, String responsebody, throwable error) {LOG.D ("ERROR", error); }        });

In the same way, you can send a JSON request with the following code:

String url = "Https://ajax.googleapis.com/ajax/services/search/images"; Asynchttpclient Client=Newasynchttpclient (); Requestparams params=Newrequestparams ();p arams.put ("Q", "Android");p Arams.put ("Rsz", "8"); Client.get (URL, params,NewJsonhttpresponsehandler () {@Override Public voidOnsuccess (intStatusCode, header[] headers, jsonobject response) {       //Handle resulting parsed JSON response here} @Override Public voidOnsuccess (intStatusCode, header[] headers, jsonarray response) {      //Handle resulting parsed JSON response here    }});

See no, the return of the response has been automatically converted into Jsonobject, of course, also support the Jsonarray type, override the version you need to do.

With Asynchttpclient, is it easy to implement these functions? Of course, this is only a very elementary introduction and use, the rest of the developers need to refer to the official

Documentation, source code (the official even provides a collection of sample usage), which is practiced in the actual project. Finally, it is strongly recommended that you use the time and tedious code to say

Bye. I have been the source of analysis, this time is no exception, the implementation of the key code I will be in the next blog specifically introduced, please look forward to, enjoy ...

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.