Android-async-http of the Fast Android Development Series Network article

Source: Internet
Author: User

Android-async-http of the Fast Android Development Series Network article

Ext.: http://www.cnblogs.com/angeldevil/p/3729808.html

Let's take a look at the basic usage.

Newnew Asynchttpresponsehandler () {    @Override    void onsuccess (String response) { SYSTEM.OUT.PRINTLN (response); }});

network requests can be performed through instances of the Asynchttpclient class, including get, put, post, head, delete. and specifies that an instance of Responsehandlerinterface receives the request result. (onsuccess parameter is not correct, here only the basic usage, detailed parameters see source code)

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.

Request process

    1. Call Asynchttpclient's Get or post methods to initiate a network request
    2. All the requests are gone sendrequest, the request is encapsulated in SendRequest in order to Asynchttprequest and added to the thread pool execution
    3. When the request is executed (that is, the Asynchttprequest Run method), the Asynchttprequest Makerequestwithretries method executes the actual request and can be retried when the request fails. and sends a message to the Responsehandlerinterface instance requesting simultaneous when the request begins, ends, succeeds, or fails
    4. Basically use the Asynchttpresponsehandler subclass, call its onstart,onsuccess and so on to return the request result
Detailed Usage methods

The official recommendation is to use a static asynchttpclient, like this:

PublicClasstwitterrestclient {PrivateStaticFinal String base_url = "http://api.twitter.com/1/";Privatestatic Asynchttpclient client =new Asynchttpclient (); public static void< Span style= "color: #000000;" > get (String URL, requestparams params, Asynchttpresponsehandler responsehandler) {client.get (Getabsoluteurl (URL), params, responsehandler); } public static void< Span style= "color: #000000;" > post (String URL, requestparams params, Asynchttpresponsehandler responsehandler) {client.post (Getabsoluteurl (URL), params, responsehandler); } private static String Getabsoluteurl (String relativeurl) {return base_url + Relativeurl; }}

The encapsulated method recommendation adds a context parameter to cancel a useless request when activity is pause or stop.

Detailed use of the method will not say, directly read the official documents

Other notes and summaries

The use of android-async-http is very simple, through the asynchttpclient to initiate the request, if you need to add parameters, directly pass a requestparams past, and the parameters can be a string, File and InputStream, you can easily upload files.

Each request needs to pass a Responsehandlerinterface instance to receive the request result or request failed, request end and so on notification, generally is Asynchttpresponsehandler subclass.

The Binaryhttpresponsehandler can initiate a binary request, such as requesting a picture.

The Texthttpresponsehandler can initiate a request to return a result as a string, which is generally used more often.

You can also use its subclass Jsonhttpresponsehandler to return the result as a jsonobject or Jsonarray. However, the sense that this class does not work, one is that there is another class Basejsonhttpresponsehandler, you can directly parse the returned JSON data, and the second is the Jsonhttpresponsehandler method is too complex, There are so many onsuccess and onfailure methods that you don't know which one to rewrite.

As shown, there are too many onsuccess and onfailure for each subclass, especially Jsonhttpresponsehandler, which should be considered a disadvantage of this kind of library. So usually use Jsonhttpresponsehandler, but directly use Texthttpresponsehandler, of course, can also use Basejsonhttpresponsehandler.

This class library is still a little bit, that is, onsuccess and other methods are generally executed in the main thread, in fact, this is not rigorous, look at the code:

PublicAsynchttpresponsehandler () {Boolean missinglooper =NULL = =Looper.mylooper ();//Try to create Handlerif (!missinglooper) handler = new Responderhandler (this); else {// There is no Looper on this thread so synchronous mode should be used. Handler = nulltrue); LOG.I (Log_tag, "current thread had not called Looper.prepare (). Forcing synchronous mode. " ); } // Init Looper by calling Postrunnable without an Argument. Postrunnable (null     

As you can see, internal use of the handler, when the new Asynchttpresponsehandler instance will get the current thread of looper, if it is empty to enable synchronous mode, that is, all callbacks will be executed in the execution of the requested thread, When it is normal to do this in a normal background thread, and we usually request it in the mainline Cheng, the result is that all callbacks are executed in the main thread, which limits our time-consuming operations in onsuccess, such as persisting the data to the database after the request succeeds.

However, we can see that the Looper object is used when creating the handler, so we can improve its constructor, add a looper parameter (synchronously modify the subclass) so that all callbacks will be executed in the Looper thread. So we just need to open up a handlerthread on the line. However, this is a disadvantage when looper is empty, and if you want to update the UI operation, you also need to send a message to the handler of the main thread for the UI to update. There is a second disadvantage, all callbacks are executed in the same handlerthread, if a process takes too long to block the subsequent request result processing, if simply write a database impact should not be small, if it takes too long, to open a thread for this time-consuming processing.

Android-async-http of the Fast Android Development Series Network article

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.