Simple use of the Android-async-http Open Source network framework in Android

Source: Internet
Author: User

The Android-async-http Open Source Network framework is an asynchronous, callback-based HTTP client built specifically for Android on an Apache basis. All requests take place outside the UI thread, and callback occurs in the thread that created it, and the handler sending message mechanism is applied to Android.

Android-async-http Features: (This section from the network)

  • Make asynchronous HTTP requests, handle responses in anonymous callbacks
  • Make an asynchronous HTTP request, and the processing response is completed in an anonymous callback
  • HTTP requests happen outside the UI thread
  • HTTP requests occur outside the UI thread
  • Requests use a threadpool to cap concurrent resource usage
  • Request use of ThreadPool to limit concurrent resource usage
  • Get/post params builder (requestparams)
  • Get/post parameter construction using (requestparams)
  • Multipart file uploads with no additional third party libraries
  • Multipart file Upload, no additional third-party libraries
  • Tiny size overhead to your application, only 25kb for everything
  • With a small overhead on your application, you can do everything in just a few kilobytes
  • Automatic Smart Request retries optimized for spotty mobile connections
  • Automated Smart request retry optimizes mobile connectivity with varying quality
  • Automatic gzip response decoding support for super-fast requests
  • Automatic decoding supports GZIP response to requests with ultra-fast speed
  • Binary file (images etc) downloading with Binaryhttpresponsehandler
  • Download binary files (images, etc.), using Binaryhttpresponsehandler
  • Built-in response parsing into JSON with Jsonhttpresponsehandler
  • Built-in response parsed into JSON, using Jsonhttpresponsehandler
  • Persistent cookie store, saves cookies into your app ' s sharedpreferences
  • Persistent cookie store, save cookies to your app's sharedpreferences

Android-async-http Open Source Library: https://github.com/loopj/android-async-http

Basic usage:

Unzip the downloaded Android-async-http Open Source Library archive package, and open the folder as shown in:

Open the "releases" folder, after each version of the jar package.

Then create a new Android project, named "Zhj_async_http". Import and add the 1.4.5 jar package to the project,

The next step is to hit the code.

First, one of the simplest uses (Request Baidu page):

Import the HTTP package.

import com.loopj.android.http.*;

Create a new Asynchttpclient instance and make a request:

New asynchttpclient (); Client.get (new    Texthttpresponsehandler () {        @Override          Public void onsuccess (int  statusCode, header[] headers, String response) {            System.out.println ( Response);        }        @Override        publicvoid onfailure (int  statusCode, header[] headers, String responsebody, throwable error) {            log.d ("error", error);        }        );

The entire procedure is as follows:

1. Create a Asynchttpclient object.

2. Use this object to set the request method (including get, put, post, head, delete).

3, incoming parameters (including the request address, parameter settings, and specify a Responsehandlerinterface instance to receive the request result ).

4. Perform the requested operation in the Onsuccess () method, and execute the request failed operation in the OnFailure () method.

What do you think? Does it feel simple?

But the official proposal uses the static way, the official demo:

Importcom.loopj.android.http.*; Public classtwitterrestclient {Private Static FinalString base_url = "http://api.twitter.com/1/"; Private StaticAsynchttpclient client =Newasynchttpclient ();  Public Static voidget (String URL, requestparams params, Asynchttpresponsehandler responsehandler) {client.get (Getabsoluteurl (URL)  , params, responsehandler); }   Public Static voidpost (String URL, requestparams params, Asynchttpresponsehandler responsehandler) {client.post (Getabsoluteurl (Ur  L), params, responsehandler); }  Private Staticstring Getabsoluteurl (String relativeurl) {returnBase_url +Relativeurl; }}
View Code
Importorg.json.*;Importcom.loopj.android.http.*;classTwitterrestclientusage { Public voidGetpublictimeline ()throwsjsonexception {twitterrestclient.get ("Statuses/public_timeline.json",NULL,NewJsonhttpresponsehandler () {@Override Public voidOnsuccess (intStatusCode, header[] headers, jsonobject response) {                //If The response is jsonobject instead of expected Jsonarray} @Override Public voidOnsuccess (intStatusCode, header[] headers, Jsonarray timeline) {                //Pull out the first event on the public timelineJsonobject firstevent = timeline.get (0); String Tweettext= Firstevent.getstring ("text"); //Do something with the responseSystem.out.println (Tweettext);    }        }); }}
View Code

Now, use the Android-async-http Open source framework to get string strings, JSON-formatted data, and network pictures.

First, use static to implement a Httputil.java (currently using only get requests) based on the official recommendation:

 Public classHttputil {Private StaticAsynchttpclient client =NewAsynchttpclient ();//instance Session Object    Static{client.settimeout (11000);//Set link timeout, if not set, default to 10s    }     Public Staticasynchttpclient getclient () {returnclient; }     Public Static voidGet (String urlstring, Asynchttpresponsehandler Res)//gets a string object with a full URL{client.get (urlstring, RES); }     Public Static voidGet (String urlstring, requestparams params, asynchttpresponsehandler res)//URL with parameters{client.get (urlstring, params, res); }     Public Static voidGet (String urlstring, Jsonhttpresponsehandler Res)//get a JSON object or array without parameters{client.get (urlstring, RES); }     Public Static voidGet (String urlstring, requestparams params, jsonhttpresponsehandler res)//with parameters to get a JSON object or array{client.get (urlstring, params, res); }     Public Static voidGet (String ustring, Binaryhttpresponsehandler Bhandler)//data will be returned with byte data.{client.get (ustring, Bhandler); }}

Implementation of the layout file:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" >    <ImageViewAndroid:id= "@+id/iv"Android:layout_width= "300DP"Android:layout_height= "300DP" />    <ScrollViewAndroid:id= "@+id/sl"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent" >        <TextViewAndroid:id= "@+id/tv"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent" />    </ScrollView></LinearLayout>

Next is Mainactivity.java (three methods are implemented to get JSON (including Jsonobject and Jsonarray), String, network image)

 Public classMainactivityextendsActivity {PrivateTextView TV; PrivateImageView IV; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); TV=(TextView) Findviewbyid (r.id.tv); IV=(ImageView) Findviewbyid (R.ID.IV);        Json ();        String ();    Image (); }    Private voidimage () {asynchttpclient client=Newasynchttpclient (); Client.get ("Http://b.hiphotos.baidu.com/zhidao/pic/item/d833c895d143ad4b08c2629580025aafa50f06f2.jpg",                NewAsynchttpresponsehandler () {@Override Public voidOnsuccess (intStatusCode, header[] headers,byte[] responsebody) {                        if(StatusCode = = 200) {Bitmapfactory Factory=Newbitmapfactory (); Bitmap Bitmap=Factory.decodebytearray (Responsebody,0, responsebody.length);                        Iv.setimagebitmap (bitmap); }} @Override Public voidOnFailure (intStatusCode, header[] headers,byte[] responsebody, throwable error)                    {Error.printstacktrace ();    }                }); }    Private voidString () {Httputil.get ("Http://www.baidu.com",NewTexthttpresponsehandler () {@Override Public voidOnsuccess (intarg0, header[] arg1, String arg2)            {Tv.settext (ARG2); } @Override Public voidOnFailure (intarg0, header[] arg1, String arg2, Throwable arg3) {Tv.settext ("Request Baidu Failed");    }        }); }    Private voidJson () {Httputil.get ("Http://m.weather.com.cn/data/101010100.html",                NewJsonhttpresponsehandler () {@Override Public voidOnsuccess (intStatusCode, header[] headers, jsonobject response) {                        //TODO auto-generated Method Stub                        Super. onsuccess (StatusCode, headers, response); if(StatusCode = = 200) {                            Try{String str=Response.getjsonobject ("Weatherinfo"). GetString ("Index_d"));                            Tv.settext (str); } Catch(jsonexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }                        } Else{Tv.settext ("StatusCode! = 200");    }                    }                }); }}

Running results such as:

(The picture on the left is the network image plus the string, the right is the network image plus the JSON data)

    

Reference Blog: http://www.open-open.com/lib/view/open1369637365753.html

Related blog: http://www.cnblogs.com/angeldevil/p/3729808.html

Official Document: http://loopj.com/android-async-http/

The code is relatively simple and the demo is not attached.

Simple use of the Android-async-http Open Source network framework in Android

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.