Android-async-http AsyncHttpClient

Source: Internet
Author: User

Android-async-http AsyncHttpClient
I just moved my house a while ago, and the company wants to release a new version. So I 've been busy and my article hasn't been updated for weeks. It's rare to be free this weekend. We found this very good third-party open-source class library, which sent http requests for Android development by accident within the week. In Android development, it is so common to send and process http requests that our code is filled with various HttpClient and smelly and long code, they exist in every corner of your code, and every time you see them, you just want the server to return a string or json to you. Every time I write such a code myself, I will think that this process cannot be simplified, and it can be done with 2 or 3 lines of code. For the simplest case, I only need to provide the request url, the callback at the time of success and the callback at the time of (or) failure. To address this problem (requirement), we can say that android-async-http provides almost perfect solutions. Using it can greatly simplify your code. In addition, your code looks more elegant. I was attracted when I first saw it, especially the async keyword. All of us in this line know that this is asynchronous execution, that is to say, its network request is automatically executed in a non-UI Thread, and you do not need any additional operations (such as manual new Thread ). Official Website of the project: callback: This is an asynchronous callback-based http client built on Apache's HttpClient. All requests occur outside the UI thread, while callback occurs in the thread where it is created, and the Android Handler sends messages. You can also apply AsyncHttpClient to the Service or background thread. The library code will automatically identify the context in which it runs. Its feature includes: 1. send an asynchronous http request and process response in an anonymous callback object; 2. http request occurs outside the UI thread; 3. the thread pool is used internally to process concurrent requests. 4. GET/POST parameter construction, through the RequestParams class. 5. built-in multipart upload without third-party library support; 6. stream Json upload without additional libraries; 7. can handle loop and relative redirection; 8. compared with the size of your app, the library size is very small, and all is only 90kb; 9. automatic and intelligent request retry mechanisms are available in various mobile connection environments; 10. automatic gzip response decoding; 11. built-in multiple forms of response Parsing, including native byte streams, strings, json objects, and even the ability to write response to files; 12. permanent cookie storage. The internal implementation uses the Android SharedPreferences. 13. use BaseJsonHttpResponseHandler to integrate with various json libraries. 14. supports the SAX Parser. 15. supports a variety of languages and content encoding, not just UTF-8. After a rough translation, these are just a general overview. The specific details have to be learned and learned slowly during use. Next, let's take a look at how code is written using android-async-http. Simply put, you only need three steps. create an AsyncHttpClient; 2. (Optional) Set Request Parameters through the RequestParams object; 3. call a get method of AsyncHttpClient to pass the callback interface implementation you need (when the call succeeds or fails), which is generally an anonymous internal class and implements AsyncHttpResponseHandler, the Class Library also provides some ready-made response handler. You generally do not need to create one by yourself. Let's see how to write the code: copy the 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) {// called when response HTTP status is "200 OK"} @ Override public void onFailure (int statusCode, Header [] header S, byte [] errorResponse, Throwable e) {// called when response HTTP status is "4XX" (eg. 401,403,404)} @ Override public void onRetry (int retryNo) {// called when request is retried}); is the copy code concise and shocking? The first time I saw it, I had a sense of mutual sorrow. It was just the way I thought about it! Here, you only need to implement AsyncHttpResponseHandler through the anonymous internal class. What's better is that you only need methods of interest to override, such as onSuccess and onFailure. The get method of this version does not pass any parameters for the request. Of course, you can also pass various parameters through RequestParams, as shown below: copy the code AsyncHttpClient client = new AsyncHttpClient (); requestParams params = new RequestParams (); params. put ("key", "value"); params. 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);} @ Ov Erride public void onFailure (int statusCode, Header [] headers, byte [] responseBody, Throwable error) {Log. d ("ERROR", error) ;}}); copy the code and the above example shows that the returned response is directly a native byte stream. If you need to treat the returned result as a String, in this case, you only need to implement a TextHttpResponseHandler anonymously. It inherits from AsyncHttpResponse and converts the native byte stream into a string object based on the specified encoding. The Code is as follows: copy the code AsyncHttpClient client = new AsyncHttpClient (); RequestParams params = new RequestParams (); params. put ("key ", "Value"); params. 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) ;}}); copy the code in the same way, you can send a json request, the Code is as follows: copy the code Strin G url = "https://ajax.googleapis.com/ajax/services/search/images"; AsyncHttpClient client = new AsyncHttpClient (); RequestParams params = new RequestParams (); params. put ("q", "android"); params. 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}); check whether the code has been copied, the returned response has been automatically converted into a JSONObject. Of course, the JSONArray type is also supported. The version you need for override is enough.

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.