0. Pre-article Gossip
As an older beginner with Android, the open-source components of Android that face a variety of poses are suffocating and difficult to cope with. Helpless in order to feed the family, although has nearly perplexed, autumnal matron, also can only sleep, one by one body position carefully study, constantly to practice, strive for early small.
Saying that it is a sunny afternoon, I sit in the corner of the street elegant network will, the product of a cup of good Coca-Cola, study Oschina client source, side by day: "Together to kill him, he did not blue ...!".
From the fire ant (Oschina client's one of the developers to salute them) there know the Async-http-client Open Source Library, in order to tens of thousands of programs have not been English class four ape GG, here to translate the author of the "User manual" first ...
1. Introduction to Async-http-client Open Source Library
Async-http-client Library is a callback function based HTTP asynchronous communication client Android component, built on the basis of Apache's HttpClient library. The async here means that all of its network requests are executed in a separate worker thread outside the main interface thread of the app. By using the message processing mechanism of Android, all of its callback functions are executed in the creation thread of the callback function. The asynchronous Http client library automatically identifies which environment to use, in addition to developing a common app, if you are using a service or background thread.
1.1 Features
asynchronously initiates an HTTP request and can handle a network response using an anonymous callback function ;
Initiates an HTTP request on a worker other than the main thread of the UI ;
The efficiency of resource concurrency is solved by using thread pool .
By using the Requestparams class, the Get/post parameters can be constructed .
Support the multipart download function of files ;
Support for uploading JSON data stream ;
Handles the redirect loop and redirects the relative path exception
Code size is small, all functions only accounted for 90kb;
Especially for the instability of mobile network, the request re-send is optimized, and the automatic intelligent processing is realized.
Data compression is supported during transmission, and the answer can be automatically gzip decompressed ;
Using binaryhttpresponsehandler, the lower level TCP/IP protocol data communication can be carried out;
Jsonhttpresponsehandler Embedded JSON parsing function, can complete JSON data parsing;
Fileasynchttpresponsehandler can save the answer to a local file directly;
supports the persistence of cookies by using the app's sharedpreferences to store cookie information;
Basejsonhttpresponsehandler can be integrated with Jackson JSON, Gson and other third-party JSON framework libraries;
Saxasynchttpresponsehandler Support for Sax parsing
In addition to UTF-8, other language encodings are supported.
1.2 Large-scale applications using Async-http-client
(The above application I have not used, anyway, it means async-http-client very diao is right)
2. Installation and basic application of Async-http-client library2.1 Basic Application Methods
1. Add in the Gradle build script
dependencies {compile ' com.loopj.android:android-async-http:1.4.8 '}
2. Introducing the HTTP Package
Import com.loopj.android.http.*;
3. Create a Asynchttpclient instance and make a request
Asynchttpclientclient = 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[] headers, byte[] errorrespoNse, throwablee) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) } @Override public void onretry (int retryno) { // called when request is retried }});
2.2 Recommended method: Create a static HTTP client
It's easier to create a static instance of Asynchttpclient to communicate using the API provided by Twitter (using Twitter as an example here, we'll take a look at the big wall):
import com.loopj.android.http.*;p ublic class twitterrestclient { private static final string base_url = "https://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&nbSp;getabsoluteurl (String relativeurl) { return base_url + relativeurl; }}
The Twitterrestclient class creates a static instance of asynchttpclient that communicates with Twitter via a static instance, with a total of two external interface functions Get,set, which are also static. Here's how to use this class in your code:
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 response is jsonobject instead of expected jsonarray } @Override public void onsuccess (int statuscode, header[] headers, jsonarray timeline) { // pull out the first event on the public timeline jsonobject firstevent = timeline.get (0); String Tweettext = firstevent.gEtstring ("text"); // Do something with the response system.out.println (Tweettext); } }); }}
The anonymous callback function is used here, and it is the Jsonhttpresponsehandler type, which embeds a JSON language parser that can be used directly in the processing function to parse the answer data JSON data, it is convenient and fast.
3. Persistent storage of cookies using Persistentcookiestore
The Async-http-client library contains a Persistentcookiestore class that implements the Cookiestore interface (originating from the Apache HttpClient package). Cookie information is automatically saved to the app's sharedpreferences storage.
This is very useful and convenient if your app needs to use cookies to maintain the user authorization session. Even if you close the app or restart the app, the app can keep the user logged in.
First create a Asynchttpclient instance:
Asynchttpclient myclient = new Asynchttpclient ();
Set up a new instance of Persistentcookiestore for this instance for cookie storage, using an activity or application when invoking the constructor of this Persistentcookiestore instance Context as a parameter (generally with this on it):
Persistentcookiestore Mycookiestore = new Persistentcookiestore (this); Myclient.setcookiestore (MyCookieStore);
Cookies that are received by the server will be automatically stored on your Android device. If you want to add your own cookie, just build a new cookie and call the Addcookie function:
Basicclientcookie Newcookie = new Basicclientcookie ("Cookiesare", "awesome"); newcookie.setversion (1); Newcookie.setdomain ("mydomain.com"); Newcookie.setpath ("/"); Mycookiestore.addcookie (Newcookie);
4. Adding get/post parameters using Requestparams4.1 Adding parameters to the request
Most of the application's URL requests require a variety of parameters to be added to the get/post request, and the Requestparams class can be used.
You can build Requestparams instances using the following three methods:
1. Create an empty Requestparams instance and add the parameters:
Requestparams params = new Requestparams ();p arams.put ("Key", "value");p arams.put ("More", "data");
2. Create a Requestparams instance with only one parameter:
Requestparams params = new Requestparams ("single", "Value");
3. Create an Requestparams instance with an existing map key value pair:
hashmap<string, string> parammap = new hashmap<string, string> ();p arammap.put ("Key", "value"); Requestparams params = new Requestparams (PARAMMAP);
4.2 Uploading files using Requestparams
The Requestparams class can also be used to implement file multipart uploads, which are implemented in three ways:
1. Add the InputStream as a parameter to the Requestparams:
InputStream myinputstream = blah; Requestparams params = new Requestparams ();p arams.put ("Secret_passwords", Myinputstream, "passwords.txt");
2. Add the file object directly to Requestparams:
File MyFile = new file ("/path/to/file.png"); Requestparams params = new requestparams (); try {params.put ("profile_picture", MyFile);} catch (FileNotFoundException e) {}
3. Use a binary byte array:
byte[] Mybytearray = blah; Requestparams params = new Requestparams ();p arams.put ("soundtrack", New Bytearrayinputstream (Mybytearray), " She-wolf.mp3 ");
5. Download binary data using Fileasynchttpresponsehandler
Fileasynchttpresponsehandler is used to obtain binary data, images, sounds and other files.
Asynchttpclient client = new Asynchttpclient (); Client.get ("Https://example.com/file.png", New fileasynchttprespons Ehandler (/* Context * *) {@Override public void onsuccess (int statusCode, header[] headers, File response) { Do something with the file ' response '}});
6. Increased authorization authentication for HTTP traffic
In a real-world application environment, some server resources require username/password authorization for access, which requires the use of the HTTP Basic Access authentication protocol for requests to be processed. You can use the Setbasicauth function to provide authentication information.
Set the username/password for host or domain access, and the default status authentication information is valid for all hosts, ports, or domain names.
Asynchttpclient client = new Asynchttpclient (), Client.setbasicauth ("username", "Password/token"); Client.get ("https ://example.com ");
A more recommended approach is to provide authorization authentication information for a specific host or port:
Asynchttpclient client = new Asynchttpclient () Client.setbasicauth ("username", "password", New Authscope ("example.c Om ", Authscope.any_realm)); Client.get (" https://example.com ");
Async-http-client Open Source Library Learning notes (i)