Android Asynchronous Http client--android Open-source network asynchronous Load Class

Source: Internet
Author: User

Organize the use of Android asynchronous Http client

Android asynchronous Http Client (AHC) a callback-type Android Network Request library is summarized:AHC is an Apache-based HttpClient library, where all network request processes take place outside the UI thread, and callbacks are handled in handler. can also be used in the service or daemon, the library will automatically identify and in the context of the corresponding processing.
Characteristics:
  1. Asynchronously sends an HTTP request that handles the response in a callback function
  2. The HTTP request process does not take place on the UI thread
  3. Using the thread pool to manage the number of concurrency
  4. Support for Get/post request parameters set separately
  5. Serialization of JSON data without additional library uploads
  6. Handle redirection
  7. Small size, only 90K
  8. Intelligent optimization of retry times for different network connections
  9. Support for gzip
  10. Binary communication protocol using Binaryhttpresponsehandler processing
  11. Built-in JSON parsing, using Jsonhttpresponsehandler to process responses
  12. to save a response directly to a file using Fileasynchttpresponsehandler
  13. Dynamically save cookies and save cookies to your app's sharedpreferences
  14. Use Basejsonhttpresponsehandler to work with the Jackson Json,gson or other JSON deserialization library
  15. Supports SAX parsing, using saxasynchttpresponsehandler
  16. Support multiple languages encoding, not just UTF-8
Who's using it?Instagram, Pinterest,pose .... How to use MVN:
<dependency>    <groupId>com.loopj.android</groupId>    <artifactId> Android-async-http</artifactid>    <version>1.4.5</version></dependency>
Guide Package:
Import com.loopj.android.http.*;
Create a Asynchttpclient object and send a request:
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 ' OK '    } @Override public    void onfailure (int statusc Ode, header[] headers, byte[] errorresponse, Throwable e) {        //Called when Response HTTP status is ' 4XX ' (eg. 401, 40 3, 404)    }    @Override public    void onretry (int retryno) {        //called If Request is retried}});

Recommended usage: Define a static HTTP client create a new network tool class that defines a global static HTTP client.

Import com.loopj.android.http.*;p Ublic class Twitterrestclient {  private static final String Base_url = "/http/ Api.twitter.com/1/";  private static Asynchttpclient client = new Asynchttpclient ();  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 static string Getabsoluteurl (String relativeurl) {      return base_url + Relativeurl;  }}

It's easy to send a network request where you need to request the Internet:

Import Org.json.*;import com.loopj.android.http.*;class twitterrestclientusage {public    void Getpublictimeline () Throws Jsonexception {        twitterrestclient.get ("Statuses/public_timeline.json", NULL, new Jsonhttpresponsehandler () {            @Override public            void onsuccess (int statusCode, header[] headers, jsonobject response) {                //If the Respon SE is jsonobject instead of expected Jsonarray            }                        @Override public            void onsuccess (int statusCode, header[] Hea DERs, Jsonarray Timeline) {//Pull out of the first event on the public                timeline                jsonobject firstevent = timeline.ge T (0);                String Tweettext = firstevent.getstring ("text");                Do something with the response                System.out.println (Tweettext);}}        );    }

API Document Http://loopj.com/android-async-http/doc/com/loopj/android/http/AsyncHttpClient.html

Use Persistentcookiestore to save cookies This library contains aPersistentCookieStore, this class is an implementation of the Apache HttpClient Cookiestore interface, which automatically saves cookies to sharedpreferences. This is especially important if you need to use cookies to keep the authentication session, because even if the user shuts down the app can still be logged in. First, create a Asynchttpclient object:
Asynchttpclient myclient = new Asynchttpclient ();

Now save the client's cookie to a persistentcookiestore, the construction method needs to have a context (activity,application can, usually this is OK).
Persistentcookiestore Mycookiestore = new Persistentcookiestore (this); Myclient.setcookiestore (MyCookieStore);

All data obtained from the server is persisted.If you want to set a cookie yourself, simply create a new cookie and call Addcookie:
Basicclientcookie Newcookie = new Basicclientcookie ("Cookiesare", "awesome"); newcookie.setversion (1); Newcookie.setdomain ("mydomain.com"); Newcookie.setpath ("/"); Mycookiestore.addcookie (Newcookie);

For details, see Persistentcookiestore Javadoc 


using Requestparams to add get/post request parametersclass Requestparams is used to add request parameters to a request, and Requestparams can be created and set up in several ways. 1. Create an empty requestparams and add the parameters:
Requestparams params = new Requestparams ();p arams.put ("Key", "value");p arams.put ("More", "data");
2. Create a requestparams with a pair of parameters
Requestparams params = new Requestparams ("single", "Value");
3. Create a map with aRequestparams
hashmap<string, string> parammap = new hashmap<string, string> ();p arammap.put ("Key", "value"); Requestparams params = new Requestparams (PARAMMAP);
For more information, please refer to: Requestparams Javadoc 

uploading files using RequestparamsRequestparams can support multimedia file upload, can be implemented in the following ways:1. Add a inputstream to the requestparams that will be uploaded
InputStream myinputstream = blah; Requestparams params = new Requestparams ();p arams.put ("Secret_passwords", Myinputstream, "passwords.txt");
2.File mode
File MyFile = new file ("/path/to/file.png"); Requestparams params = new requestparams (); try {    params.put ("Profile_picture", MyFile);} catch ( FileNotFoundException e) {}
3.byte Array Form
byte[] Mybytearray = blah; Requestparams params = new Requestparams ();p arams.put ("soundtrack", New Bytearrayinputstream (Mybytearray), " She-wolf.mp3 ");

Details: Requestparams Javadoc 
using Fileasynchttpresponsehandler to download binary filesclass Fileasynchttpresponsehandler can be used to obtain binary files, slices, voice and other files:
Asynchttpclient client = new Asynchttpclient (); Client.get ("Http://example.com/file.png", new Fileasynchttpresponsehandler () {    @Override public    void onsuccess (int statusCode, header[] headers, File Response) {        //do something with the file ' response '}    });

Details: Fileasynchttpresponsehandler Javadoc 
Add a Basic authentication voucherSome requests may require credentials like Username/password
Asynchttpclient client = new Asynchttpclient (), Client.setbasicauth ("username", "Password/token"); Client.get ("http:/ /example.com ");

Of course you can also customize
Asynchttpclient client = new Asynchttpclient () Client.setbasicauth ("username", "password", New Authscope ("example.com (Authscope.any_realm)); Client.get ("http://example.com");

Details: Requestparams Javadoc
Description Document: Http://loopj.com/android-async-http/GITHUB Address: Https://github.com/loopj/android-async-httpMVN Address:/http central.maven.org/maven2/com/loopj/android/android-async-http/

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.