Android Open Source Library--asynchronous HTTP client asynchronous HTTP clients

Source: Internet
Author: User

If I look farther than others, it is because I stand on the shoulders of giants.

GitHub Address: Https://github.com/loopj/android-async-http

API Document Address: http://loopj.com/android-async-http/doc/

HTTP communication as the development of Android's most basic module, I believe you will need to develop network applications.

When I first came to Android, I realized a simple HTTP communication module by using Apache's HttpClient class library, thread safety, creating a new thread each time, and completing asynchronous loading through hander.

The library was found later on GitHub, similar in principle to Apache's httpclient, while the official Android class library was httpurlconnection.

There is no serious study of the source code, design package is very good, today, the main introduction of this class library.

Introduced

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
Main class Introduction
    • Asynchttprequest

Inherit from Runnabler, submit to thread pool to execute network request and send start,success message

    • Asynchttpresponsehandler

Receive request results, General rewrite onsuccess and onfailure receive requests for success or failure messages, and onstart,onfinish messages

    • Texthttpresponsehandler

Inherit from Asynchttpresponsehandler, just rewrite the Asynchttpresponsehandler onsuccess and OnFailure methods to convert the request result from a byte array to a string

    • Jsonhttpresponsehandler

Inherits from Texthttpresponsehandler, also overrides the Onsuccess and OnFailure methods, converting the request result from a string to a jsonobject or Jsonarray

    • Basejsonhttpresponsehandler

Inherits from Texthttpresponsehandler, is a generic class, provides the Parseresponse method, the subclass needs to provide the implementation, the request result resolves to the need type, the subclass can use the Analytic method flexibly, can the direct primitive parsing, uses the Gson and so on.

    • Requestparams

Request parameter, can add normal string parameter, and can add File,inputstream upload file

    • Asynchttpclient

Core class, using HttpClient to perform network requests, provide get,put,post,delete,head and other request methods, easy to use, simply call the URL and requestparams the appropriate method, you can optionally pass in the context To cancel a content-related request and must provide an implementation class that Responsehandlerinterface (Asynchttpresponsehandler inherits from Responsehandlerinterface), Typically a subclass of Asynchttpresponsehandler, Asynchttpclient has a thread pool inside, and when you use Asynchttpclient to perform a network request, the SendRequest method is eventually called. Within this method, the request parameters are encapsulated as asynchttprequest (inherited from Runnable) and executed by the internal thread pool.

    • Synchttpclient

Inherits from Asynchttpclient, synchronously executes the network request, Asynchttpclient submits the request to the thread pool after encapsulation asynchttprequest, Synchttpclient calls its run method directly after encapsulating the request as a asynchttprequest.

Use the method on the official website to write more detailed, the demo inside also have, everybody see to understand

The above contents refer to:

Http://www.cnblogs.com/angeldevil/p/3729808.html

http://blog.csdn.net/qduningning/article/details/34829429

The current mainstream data are in the rest mode, JSON format communication, because I still prefer gson (because it can be directly generic conversion), Jsonhttpresponsehandler used not used. In the actual project I also encapsulated once, using Texthttpresponsehandler to obtain the results, with Gson parsing.

Package of Android-async-http

Importcom.loopj.android.http.AsyncHttpClient;ImportCom.loopj.android.http.AsyncHttpResponseHandler;ImportCom.loopj.android.http.RequestParams; Public classResthttputils {Private StaticAsynchttpclient client =Newasynchttpclient (); Static{Client.addheader ("Accept", "Application/json"); }     Public Static voidget (String URL, requestparams params, Asynchttpresponsehandler responsehandler) {client.get (URL, params, resp    Onsehandler); }     Public Static voidget (String URL, Asynchttpresponsehandler responsehandler) {client.get (URL,NULL, ResponseHandler); }     Public InterfaceResthttphandler<t> {         Public  voidonsuccess (T result); }}

Package of Gson

 Public class gsonutils {    privatestaticnew  Gson ();      Public static <T> T Parse (String JSON, class<t> t) {        return  _ Gson.fromjson (JSON, T);    }      Public static <T> T parselist (String json, type type) {        return  _ Gson.fromjson (JSON, type);}    }

Business logic Controller

public class Controller {
Public Static voidGetdetail (FinalContext CTX,intIdFinalResthttphandler<entity>handler) {Resthttputils.get (Apiurls.getdetail ()+ "/id/" + ID,NewTexthttpresponsehandler () {@Override Public voidOnFailure (intarg0, header[] arg1, String arg2, Throwable arg3) {Toast.maketext (CTX,"Get details Failed", Toast.length_short). Show (); } @Override Public voidOnsuccess (intarg0, header[] arg1, String arg2) {Entity result= Gsonutils.parse (Arg2, Entity.class); Handler.onsuccess (result); } }); }
}

Specific use

Controller.getdetail (detailactivity.  this, getintent (). Getintextra ("Id", 0),                new resthttphandler<entity>() {                    @ Override                    publicvoid  onsuccess (Entity result) {
Get results, make a series of UI actions }
});

Android Open Source Library--asynchronous HTTP client asynchronous HTTP clients

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.