Android's Async-http

Source: Internet
Author: User

Brief introduction:

Async-http is a foreign open source framework, the author is loopj. is based on the Apache HttpClient Library. It can make the network data request and send, file download and upload conveniently and quickly and efficiently.


Characteristics:

A clear network request callback
Request use of ThreadPool to limit concurrent resource usage
Get/post based on parameter construction (REQUESTPARAMS) for easy
Multipart file upload, big data upload download
Automated Smart request retry optimizes mobile connectivity with varying quality

Built-in response parsed into JSON, using Jsonhttpresponsehandler

Persistent cookie store, save cookies to your app's sharedpreferences
Download binary files (images, etc.), using Binaryhttpresponsehandler


Usage:

The build request first establishes the request client object.
The corresponding get and post requests are then made, and the request results are parsed in the callback.
Async-http's get and post requests can be based on parameterized requests (requestparams), which make it clear and convenient to put your request parameters inside, then get and post requests.


Example:

First we need to select a Network Service API, here I choose the aggregation data inside the cell phone attribution to query api,1 Registration 2 application, after the application will be assigned to your application a appkey, the following is the API description:

/*** interface Address: Http://apis.juhe.cn/mobile/get support format: Json/xml Request method: Get/post Request Example: http://apis.juhe.cn/mobile/get?phone= 13429667914&key= The key request parameter you requested: name type required Description Phoneint is the mobile phone number or mobile phone number that needs to be queried the first 7 keystring is the app Appkey (Application Detail page query) Dtypestring no return data format, XML or JSON, default JSON call sample and Debug tool:  API test Tool return field: Name type description error_codeint return code reasonstring return description Resultstring return result set provincestring province citystring City areacodestring area code zipstring zip companystring operator cardstring card type **/
before using Async-http, the jar package must be put into the project, and I've written a sample code like this:

public class Mainactivity extends Activity implements onclicklistener{//GET request mode urlprivate static final String Url_get = "HTTP://APIS.JUHE.CN/MOBILE/GET?PHONE=18952201314&KEY=A53155CC6AF64DAABC66655B060DB56A";// Urlprivate static final String url_post = "Http://apis.juhe.cn/mobile/get?" of the POST request mode; /Declare a asynchttpclient variable private asynchttpclient asynchttpclient = null; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); SetupViews (); Initasynchttp ();} @Overridepublic void OnClick (View v) {int id = v.getid (); switch (ID) {Case r.id.button1://submits the request Asynchttpget () by a Get method; Case r.id.button2://Submit Request Asynchttppost (); break;default:break;}} private void Setupviews () {Findviewbyid (r.id.button1). Setonclicklistener (this); Findviewbyid (R.id.button2). Setonclicklistener (this);} Initialize asynchttpprivate void Initasynchttp () {asynchttpclient = new asynchttpclient ();} private void Asynchttpget () {///When GET request is sent, OnStart, onsuccess or OnFailure, OnFinish method will be callback Asynchttpclient.get (Url_get, New Asynchttpresponsehandler () {@Overridepublic void OnStart () {System.out.println ("Get request OnStart ..."); Super.onstart (); @Overridepublic void onsuccess (String arg0) {string result = arg0;//If the result is to be encapsulated as an object by JSON parsing, refer to the volley of Android The code in SYSTEM.OUT.PRINTLN (result); super.onsuccess (arg0);} @Overridepublic void OnFailure (Throwable arg0) {System.out.println ("Get request onfailure ..."); Super.onfailure (arg0) ;} @Overridepublic void OnFinish () {System.out.println ("Get request onfinish ..."); Super.onfinish ();}}); private void Asynchttppost () {//New Requestparams object used to store the parameters of the POST request Requestparams Requestparams = new Requestparams ();// Set Request parameters Requestparams.put ("Phone", "18952201314"), Requestparams.put ("Key", "a53155cc6af64daabc66655b060db56a");// When the POST request is sent, the OnStart, onsuccess, or OnFailure, onfinish methods will be called back in turn//Because the returned data is in JSON format, So the handler here can be chosen as Jsonhttpresponsehandlerasynchttpclient.post (Url_post, Requestparams, new Jsonhttpresponsehandler () {@Overridepublic VOID OnStart () {System.out.println ("POST request OnStart ..."); Super.onstart (); @Overridepublic void onsuccess (Jsonobject arg0) {//Here the callback parameter is directly the Jsonobject type, eliminating our program System.out.println (arg0.tostring ()); super.onsuccess (arg0);} @Overridepublic void OnFailure (Throwable arg0) {System.out.println ("POST request onfailure ..."); Super.onfailure (arg0 );} @Overridepublic void OnFinish () {System.out.println ("POST request onfinish ..."); Super.onfinish ();}});}}


The entire project code compression package is as follows and needs to be downloaded:

Android async-http Demo

Android's 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.