Android Network Interaction

Source: Internet
Author: User

One

In Android, sending and processing HTTP requests is so common that we often need to write this code.

The code for network interaction in Android cannot be executed in the UI thread, only in the additional child threads.

My general practice is to complete the code of the network interaction by creating a child thread and handler, and the result of the interaction is fed back to the UI thread through handler.

New Thread () {            publicvoid  run () {                ////HTTP request send and receive                code // handler the action interface through the notification page             };        }. Start ();

Another way to interact is through the callback function callback.

Two

A library of network interactions was found: android-async-http, trying to use it a little while ago, felt pretty good.

This library, the code of his network interaction has been encapsulated in the inside, usually an HTTP request only a few simple lines of code to complete.

It interacts with the UI through the callback function callback to achieve, the content is completed, where the start of the network interaction, the end, success, failure, progress, etc. can be obtained through callback

First step: Get HttpClient Object

New Asynchttpclient (); This step allows us to package ourselves into a single-case pattern

Step two: Send a GET request

Client.get (url.tostring (), ResponseHandler);
ResponseHandler of this place, if we need to get the relevant return value of this request, we need to rewrite the implementation of this class, and rewrite the method, if not necessary, use NULL instead of Jsonhttpresponsehandler ResponseHandler=NewJsonhttpresponsehandler () { Public voidOnsuccess (intStatusCode, org.apache.http.header[] headers, org.json.JSONObject response) { Super. onsuccess (StatusCode, headers, response); }; Public voidOnFailure (intStatusCode, org.apache.http.header[] headers, throwable throwable, Org.json.JSONObject errorresponse) { Super. OnFailure (StatusCode, headers, throwable,}; @Override Public voidonfinish () {Super. OnFinish (); };
There are many other methods that can be overridden, basically including all the States in the interaction process
}

Three

Think this library writing is very good, all kinds of tall, simple read a bit of the source, he is open source on GitHub.

Each request is encapsulated in a runnable, and when the request is executed, Executorservice.submit (runnable) executes the runnable in the thread pool.

Create Httpurirequest objects based on user-supplied network path and key-value pairs, and perform network operations via HttpResponse response = Client.execute (Httpurirequest, HttpContext)

Httpurirequest, which is an interface that has multiple subclasses, which contains httpentityenclosingrequestbase;httpentityenclosingrequestbase containing Seturi () and setEntity(HttpEntity entity) The method.

After the request is sent, the method returns an object called RequestHandle, through which the Cancel method of the object can implement the method of canceling the request

This is just a description of the main methods in the library, and there are many other things, such as gzip, such as base64, etc.

Four

Features that are included:

1. Send an asynchronous HTTP request to process response in an anonymous callback object; 2. HTTP requests occur outside the UI thread; 3. The internal thread pool is used to handle concurrent requests; 4. The Get/post parameter is constructed through the Requestparams class. 5. Built-in multipart file upload, do not need third-party library support; 6. Streaming JSON uploads, no additional libraries required; 7. Capable of handling circular and relative redirects; 8. Compared to your app size, the library's size is small, everything is only 90kb; 9. Automatic Intelligent request retry mechanism in a variety of mobile connected environments; 10. Automatic gzip response decoding; 11. Built-in various forms of response parsing, there are native byte stream, String,json object, even can write response to the file; 12. Permanent cookie preservation, internal implementation using Android Sharedpreferences; 13. Integrated through Basejsonhttpresponsehandler and various JSON libraries; 14. Support SAX parser; 15. supports a variety of languages and content encodings, not just UTF-8.

Android Network Interaction

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.