Android Asynchronous Http Client

Source: Internet
Author: User
Tags glu games

Features
  • Make asynchronous HTTP requests, handle responses in anonymous callbacks
  • HTTP requests happen outside the UI thread
  • Requests use a threadpool to cap concurrent resource usage
  • Get/post params builder (requestparams)
  • Multipart file uploads with no additional third party libraries
  • Streamed JSON uploads with no additional libraries
  • Handling circular and relative redirects
  • Tiny size overhead to your application, only 90kb for everything
  • Automatic Smart Request retries optimized for spotty mobile connections
  • Automatic gzip response decoding support for super-fast requests
  • Binary protocol communication withBinaryHttpResponseHandler
  • Built-in response parsing into JSON withJsonHttpResponseHandler
  • Saving response directly into file withFileAsyncHttpResponseHandler
  • Persistent Cookie Store, saves cookies into your app ' s sharedpreferences
  • Integration with Jackson JSON, Gson or other json (DE) serializing libraries withBaseJsonHttpResponseHandler
  • Support for SAX parser withSaxAsyncHttpResponseHandler
  • Languages and content encodings, not just UTF-8
Used in Production by Top Apps and developers
Instagram
Instagram is the #1 photo app on Android, with over 10million users
Pinterest
Popular online Pinboard. Organize and share things you love.
Frontline Commando (Glu games)
#1 first person shooting game on Android with Glu games.
Heyzap
Social game discovery app with millions of users
Pose
Pose is the #1 fashion app for sharing and discovering new styles
Thousands More Apps ...
Async HTTP is used in production by thousands of top apps.
Installation & Basic Usage

ADD maven dependency using Gradle buildscript in format

dependencies {  compile ‘com.loopj.android:android-async-http:1.4.5‘}

Import the HTTP package.

import com.loopj.android.http.*;

Create a new AsyncHttpClient instance and make a request:

Asynchttpclient client =Newasynchttpclient (); Client.get ("Http://www.google.com",NewAsynchttpresponsehandler () {@Override Public voidOnStart () {//called before request is started} @Override Public voidOnsuccess (intStatusCode, header[] headers,byte[] response) {        //called when response HTTP status is " OK"} @Override Public voidOnFailure (intStatusCode, header[] headers,byte[] errorresponse, Throwable e) {        //called when response HTTP status is "4XX" (eg. 401, 403, 404)} @Override Public voidOnretry (intRetryno) {        //called when request is retried    }});

Recommended Usage:make a Static Http Client

In this example, we'll make an HTTP client class with the static accessors to make it easy-to-communicate with Twitter ' s API.

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; }}

This and then makes it very easy-to-work with the Twitter API in your 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);    }        }); }}

Check out the asynchttpclient, Requestparams and Asynchttpresponsehandlerjavadocs for more details.

Persistent Cookie Storage with PersistentCookieStore

This library also includes a which are an implementation of the PersistentCookieStore Apache HttpClient CookieStore interface that automatically Saves cookies to SharedPreferences storage on the Android device.

This is extremely useful if your want to use cookie to manage authentication sessions, since the user would remain logged I n even after closing and re-opening your app.

First, create an instance of AsyncHttpClient :

New Asynchttpclient ();

Now set the this client's Cookie store to is a new instance PersistentCookieStore of, constructed with an activity or application context (USU Ally would this suffice):

New Persistentcookiestore (this); Myclient.setcookiestore (Mycookiestore);

Any cookie received from servers'll now is stored in the persistent cookie store.

To add your own cookies to the store, simply construct a new cookie and call addCookie :

New Basicclientcookie ("Cookiesare", "awesome"); Newcookie.setversion (1); Newcookie.setdomain (" MyDomain.com "); Newcookie.setpath ("/"); Mycookiestore.addcookie (Newcookie) ;

See the Persistentcookiestore Javadoc for more information.

Adding Get/post Parameters with RequestParams

The RequestParams class is used to add optional GET or POST parameters to your requests. RequestParams can being built and constructed in Var IOUs ways:

Create empty and RequestParams immediately add some parameters:

New requestparams ();p arams.put("Key", "value");p arams.put ("More", "data");

Create for RequestParams a single parameter:

New Requestparams ("single", "Value");

Create from an RequestParams existing of Map Key/value strings:

New Hashmap<string, string>();p arammap.put ("key", "value",new Requestparams ( PARAMMAP);

See the Requestparams Javadoc for more information.

Uploading Files with RequestParams

The RequestParams class additionally supports multipart file uploads as follows:

Add to the InputStream RequestParams upload:

InputStream Myinputstream =new  requestparams ();p arams.put ("Secret_passwords", Myinputstream, "Passwords.txt");

Add a File object to the RequestParams upload:

New File ("/path/to/file.png"new  requestparams (); Try {    params.put ("profile_picture"catch(FileNotFoundException e) {}

ADD a byte array to the RequestParams upload:

byte [] Mybytearray =new  requestparams ();p arams.put (New Bytearrayinputstream (Mybytearray), "She-wolf.mp3");

See the Requestparams Javadoc for more information.

Downloading Binary Data with FileAsyncHttpResponseHandler

The FileAsyncHttpResponseHandler class can is used to fetch binary data such as images and other files. For example:

New asynchttpclient (); Client.get (new fileasynchttpresponsehandler (/** /  This ) {    @Override    publicvoid onsuccess (int  statusCode, header[] Headers, file response) {        // do something with the File ' response '}    });

See the Fileasynchttpresponsehandler Javadoc for more information.

Adding HTTP Basic Auth Credentials

Some requests may need username/password credentials when dealing with API services This use HTTP Basic Access authenticat Ion requests. You can use the method to setBasicAuth() provide your credentials.

Set Username/password for any host and realm for a particular request. By default of the authentication Scope is to any host, port and realm.

New asynchttpclient (); Client.setbasicauth ("username", "Password/token"); Client.get ("http://example.com");

You can also provide a more specific authentication Scope (recommended)

New asynchttpclient (); Client.setbasicauth (new authscope ("example.com",Authscope.any_realm) ); Client.get ("http://example.com");

See the Requestparams Javadoc for more information.

Testing on Device

You can test the library on real device or emulator using provided Sample application. Sample application implements all important functions of the library, you can use it as source of inspiration.

Source Code of Sample Application:https://github.com/loopj/android-async-http/tree/master/sample

To run sample application, clone the Android-async-http GitHub repository and Run command in it ' s root:

gradle :sample:installDebug

Which would install Sample application on connected device, all examples does work immediately, and if not please file bug report On Https://github.com/loopj/android-async-http/issues

Building from Source

To build a .jar file from source, first make a clone of the Android-async-http GitHub repository. Then you have the installed Android SDK and Gradle Buildscript, then just run:

gradle :library:jarRelease

This would generate a file in path {repository_root}/library/build/libs/library-1.4.6.jar .

Reporting Bugs or Feature requests

Bugs or feature requests on the GitHub issues page for this project here:

Https://github.com/loopj/android-async-http/issues

Credits & Contributors
James Smith (HTTP://GITHUB.COM/LOOPJ)
Creator and Maintainer
Marek Sebera (Http://github.com/smarek)
maintainer since 1.4.4 release
Noor Dawod (Https://github.com/fineswap)
maintainer since 1.4.5 release
Luciano Vitti (https://github.com/xAnubiSx)
collaborated on Sample application
Jason Choy (Https://github.com/jjwchoy)
Added support for RequestHandle feature
Micah Fivecoate (HTTP://GITHUB.COM/M5)
Major contributor, including the original RequestParams
The Droid Fu Project (HTTPS://GITHUB.COM/KAEPPLER/DROID-FU)
inspiration and code for better HTTP retries
Rafael Sanches (http://blog.rafaelsanches.com)
Original SimpleMultipartEntity Code
Anthony Persaud (Http://github.com/apersaud)
Added support for HTTP Basic authentication requests.
Linden Darling (Http://github.com/coreform)
Added support for binary/image responses

And many others, contributions is listed in each file in license header. You can also find contributors by looking on project commits, issues and pull-requests Ongithub

License

The Android asynchronous Http Client is released under the android-friendly Apache License, Version 2.0. Read the full license here:

http://www.apache.org/licenses/LICENSE-2.0

About the Author

James Smith, British entrepreneur and developer based in San Francisco.

I ' m the co-founder of Bugsnag with Simon Maynard, and from-to-I led up the product team as CTO of Heyzap.

Follow @loopj

Android Asynchronous Http Client

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.