TOP1 Android Asynchronous network request framework on Github

Source: Internet
Author: User

Today we share a basic usage of the Android Asynchronous network request framework on GitHub, and I'll share it with TOP1.

Let's start with a simple GET request.

Asynchttpclient client =NewAsynchttpclient (); Client.get ("http://www.google.com",NewAsynchttpresponsehandler () {@Override     Public void OnStart() {//called before request is started}@Override     Public void onsuccess(intStatusCode, header[] headers,byte[] response) {//Called when response HTTP status is " OK"}@Override     Public void onfailure(intStatusCode, header[] headers,byte[] errorresponse, Throwable e) {//Called when response HTTP status is "4XX" (eg. 401, 403, 404)}@Override     Public void Onretry(intRetryno) {//Called when request is retried}});

So with every time we have to new very troublesome, we can simply encapsulate, directly call the static method, and the domain name is added uniformly, automatically converted to the final URL request address

Importcom.loopj.android.http.*; Public  class twitterrestclient {  Private Static FinalString Base_url ="http://api.twitter.com/1/";Private StaticAsynchttpclient client =NewAsynchttpclient (); Public Static void Get(String URL, requestparams params, Asynchttpresponsehandler ResponseHandler)  {client.get (Getabsoluteurl (URL), params, responsehandler); } Public Static void Post(String URL, requestparams params, Asynchttpresponsehandler ResponseHandler)  {client.post (Getabsoluteurl (URL), params, responsehandler); }Private StaticStringGetabsoluteurl(String Relativeurl) {returnBase_url + Relativeurl; }}

This is then used, and the request returns a JSON-type return value

Twitterrestclient.get ("Statuses/public_timeline.json",NULL,NewJsonhttpresponsehandler () {@Override        Public void onsuccess(intStatusCode, header[] headers, jsonobject response) {//If The response is jsonobject instead of expected Jsonarray}@Override        Public void onsuccess(intStatusCode, header[] headers, Jsonarray timeline) {The first event on the public timelineJsonobject firstevent = Timeline.get (0); String Tweettext = firstevent.getstring ("Text");//Do something with the responseSystem.out.println (Tweettext); }   });

Add Get/post parameter Requestparams

//set up empty RequestParams And immediately add some parameters:  requestparams params = new  requestparams ();p arams.put ( "key" ,  "value" );p Arams.put (  "more" ,  "data" ); //create requestparams one parameter:  Requestparams params = new  requestparams ( "single" , ); //create Requestparams string from existing map key/value:  hashmap<string, string> parammap = new  hashmap<string, String> (); Parammap.put ( "key" ,  "value" ); Requestparams params = new  requestparams (parammap);  

Uploading Files Requestparams

//Add a InputStream to Requestparams upload:InputStream myinputstream = blah; Requestparams params =NewRequestparams ();p arams.put ("Secret_passwords", Myinputstream,"Passwords.txt");//Add a requestparams upload of a file object:File MyFile =NewFile ("/path/to/file.png"); Requestparams params =NewRequestparams ();Try{Params.put ("Profile_picture", myFile);}Catch(FileNotFoundException e) {}//Add an array of bytes Requestparams upload:byte[] Mybytearray = blah; Requestparams params =NewRequestparams ();p arams.put ("Soundtrack",NewBytearrayinputstream (Mybytearray),"She-wolf.mp3");

Download data data, Fileasynchttpresponsehandler

#FileAsyncHttpResponseHandler classes can be used to get binary data photos and other files. For example:
new AsyncHttpClient();client.get("http://example.com/file.png"new FileAsyncHttpResponseHandler(/* Context */this) {    @Override    publicvoidonSuccess(int statusCode, Header[] headers, File response) {        // Do something with the file `response`    }});

Add HTTP Basic Authentication credentials

//some requests may require a username/ The password credential in the processing API uses the HTTP Basic authentication request to access the service. You can use this method to provide your credentials Setbasicauth ().  //set the username/password for any host and domain-specific requests. By default, any host's certification range, port and domain.  asynchttpclient client = new  asynchttpclient (); Client.setbasicauth ( "username" ,  "Password/token" ); Client.get ( "http://example.com" ); //You can also provide a more specific scope of certification (recommended)  Asynchttpclient client = new  asynchttpclient (); Client.setbasicauth (" username ", " password ", new  Authscope ( "example.com" , 80 , Authscope.any_realm) client.get ();  

Persistent cookie Storage and Persistentcookiestore

//This library also contains a persistentcookiestore which is an implementation of the Apache HttpClient Cookiestore interface, automatically save cookies, sharedpreferences stored on Android devices. //This is very useful if you want to use a cookie to manage the authentication session because the user will continue to log on even if the restart application is turned off. ///First, create an instance of Asynchttpclient:Asynchttpclient myclient =NewAsynchttpclient ();///Now a new instance of this customer's cookie store is persistentcookiestore by an activity or application context (which is usually enough):Persistentcookiestore Mycookiestore =NewPersistentcookiestore ( This); Myclient.setcookiestore (Mycookiestore);//Any cookie received by the server will be stored in the persistent cookiestore. //Add your own cookiestore, just build a new cookie and call Addcookie:Basicclientcookie Newcookie =NewBasicclientcookie ("Cookiesare","Awesome"); Newcookie.setversion (1); Newcookie.setdomain ("mydomain.com"); Newcookie.setpath ("/"); Mycookiestore.addcookie (Newcookie);

Download | Click here

GitHub Address | Click here

/** * -------------- * 欢迎转载   |  转载请注明 * -------------- * @author zsl * @github https://github.com/yy1300326388 * @blog http://blog.csdn.net/yy1300326388 */

TOP1 Android Asynchronous network request framework on Github

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.