Android-async-http asynchttpclient Introduction

Source: Internet
Author: User

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. Compared to the size of your app, the library has a small size and everything is only 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. Integration through Basejsonhttpresponsehandler and 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 = new Asynchttpclient (); Client.get ("http://www.google.com", new Asynchttpresponsehandler () {     @Override public    void OnStart () {        //called before request was started    }     @Override public    Void onsuccess (int statusCode, header[] headers, byte[] response) {        //Called when response HTTP status is "OK"    }< c11/> @Override public    void onfailure (int statusCode, header[] headers, byte[] errorresponse, Throwable e) {        // Called when response HTTP status was "4XX" (eg. 401, 403, 404)    }     @Override public    void onretry (int retryno) {        //Called when request is retried    }});

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 = new Asynchttpclient (); Requestparams params = new Requestparams ();p arams.put ("Key", "value");p arams.put ("More", "data"), Client.get ("http:// Www.google.com ", params, new    Asynchttpresponsehandler () {        @Override public        void onsuccess (int statusCode , header[] headers, byte[] response) {            System.out.println (response);        }         @Override public        void onfailure (int statusCode, header[] headers, byte[] responsebody, throwable error) {            LOG.D ( "Error", error);        }        );

Texthttpresponsehandler, which inherits from the Asynchttpresponse, and converts the native byte stream into a string object,  code as specified by encoding: asynchttpclient Client = new Asynchttpclient (); Requestparams params = new Requestparams ();p arams.put ("Key", "value");p arams.put ("More", "data"), Client.get ("http:// Www.google.com ", params, new    Texthttpresponsehandler () {        @Override     & nbsp   public void onsuccess (int statusCode, header[] headers, String response) {            SYSTEM.OUT.PRINTLN (response);       }         @Override     &NBSP ;   public void onfailure (int statusCode, header[] headers, String responsebody, throwable error) {            LOG.D ("error", error);       }       });
Asynchttpclient client = new Asynchttpclient (); Requestparams params = new Requestparams ();p arams.put ("Key", "value");p arams.put ("More", "data"), Client.get ("http:// Www.google.com ", params, new    Texthttpresponsehandler () {        @Override public        void onsuccess (int statusCode, Header[] headers, String response) {            System.out.println (response);        }         @Override public        void onfailure (int statusCode, 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 = new Asynchttpclient (); Requestparams params = new Requestparams ();p arams.put ("Q", "Android");p arams.put ("Rsz", "8"); Client.get (URL, params, New Jsonhttpresponsehandler () {                @Override public    void onsuccess (int statusCode, header[] headers, jsonobject Response) {       //Handle resulting parsed JSON response here    }    @Override public    void onsuccess (int StatusCode, 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.

Android-async-http asynchttpclient Introduction

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.