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.

  found this great third-party open source class library that sends HTTP requests for Android development.   in Android development, sending and processing HTTP requests is so common that our code is littered with all kinds of httpclient and related, smelly, long code,  they exist in every corner of your code, and every time you see it is disgusting, And you just want the server to return a string or JSON to you. Every time I write this kind of   code myself, I want to be able to simplify the process, perhaps 2 or 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 failure of the 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 can greatly simplify your code, not only that, your code looks much more elegant.   I was attracted when I first saw it, especially the Async keyword, as we know in this line, this is asynchronous execution, which means that its network request is automatically executed in a non-ui  thread, and you don't need any extra action (such as manually new thread, etc.). Official website of the project:  http://loopj.com/android-async-http/, corresponding GitHub address: https://github.com/loopj/android-async-http   Here is a brief introduction: It is an asynchronous callback-based HTTP client built specifically for Android on the httpclient basis of Apache. All requests   occurs 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 a  service or background thread, and the library code will automatically recognize the context it is running on. Its feature include:  1. Sends an asynchronous HTTP request to process the response; 2 in an anonymous callback object. HTTP requests occur outside the UI thread;  3. The internal thread pool is used to handle concurrent requests;  4. The Get/post parameter is constructed through the Requestparams class.  5. Built-in multipart file upload, do not need third-party library support; 6. Streaming JSON uploads, no additional libraries required;  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 connected environments;  10. Automatic gzip response decoding;  11. Built-in various forms of response parsing, there are native byte stream, String,json object, and even can write response to the file;  12. Persistent cookie preservation, internal implementation using Android SHAREDPREFERENCES; 13. Integrated through Basejsonhttpresponsehandler and various JSON libraries;  14. Support sax parser;  15. supports a variety of languages and content encodings, not just UTF-8.   Probably translated, these are just a general overview, specific details have to be used in the process of slowly feeling, learning.   Next, take a look at the application of Android-async-http to write code what it looks like. Simply put, you only need 3 steps,  1. Create a asynchttpclient; 2. (optional) Set the request parameters through the Requestparams object;  3. Call Asynchttpclient of a Get method, passing you need (success and failure) callback interface implementation, generally anonymous internal class &nbsp, implemented Asynchttpresponsehandler, The class library itself also offers a number of ready-made response handler, which you don't normally need to create yourself.   to see how the code writes:  copy code asynchttpclient client = new Asynchttpclient (); Client.get ("http://www.google.com", new Asynchttpresponsehandler () {     @Override     public void OnStart () {        Called before request is started   }     @Override    public void onsuccess (int statusCode, header[] headers, byte[] response) {       //C alled when response HTTP status is "$ OK"    }     @Override     public void onfailure (int statusCode, header[] headers, byte[] errorresponse, Throwable e) {       //Called when response HTTP status is "4XX" (eg. 401, 403, 404)    }   & nbsp @Override     public void Onretry (int. retryno) {       //Called when request is Retried&nbs P  }); Copy the code 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! You only need to implement Asynchttpresponsehandler by   anonymous internal classes, 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, of course you can also pass various parameters through Requestparams, as follows:  copy code 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&nbsP   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);       }       }); Copy code above example is returned response directly is the original word throttling situation, If you need to treat the returned result as a string, you only need to implement a  texthttpresponsehandler anonymously, which inherits from Asynchttpresponse, and converts the native byte stream into a string object based on the specified encoding,  code:  copy code 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 () {      &NBSP @Override         public void onsuccess (int statusCode, header[] headers, String response) {  &nbs P         SYSTEM.OUT.PRINTLN (response);       }         @O verride        public void onfailure (int statusCode, header[] headers, String responsebody, Throwable Error) {            LOG.D ("error", error);       }       ); Copy the code the same way you can send a JSON request, code as follows:  copy 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 statusco DE, header[] headers, jsonarray response) {     //Handle resulting parsed JSON response here    }}); Copy the code see No, the returned response has been automatically converted to Jsonobject, of course, also support Jsonarray type, override the version you need to do it.

Android-async-http asynchttpclient Introduction

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.