Android's Volley

Source: Internet
Author: User

Brief introduction:

Volley is a network communication library on Google I/O 2013 on an Android platform that is officially released by Google.
Previous network requests, consider opening threads, memory leaks, performance, and so on complex issues. But the volley framework has helped us to deal with these problems, and provide the corresponding perfect request API, we only need to use as required.


Characteristics:

Makes network communication faster, simpler, and more robust
High-efficiency asynchronous processing requests for Get, post network requests, and network images
Network requests can be prioritized for management
Caching of Network requests
Multi-level cancellation requests
Linkage with activity lifecycle (all network requests are canceled at the end of activity)
Using volley can simplify the development of some network communications, although volley is not suitable for big data (large payloads) and streaming media network requests. For example, hundreds of megabytes of files, video download.
Volley open source, can be customized modifications can also be directly used in the form of jar package.


Usage:

Volley how to use the Get and post requests
Volley network request queue to establish and cancel queue requests


The setup request first establishes the queue and adds the request to the request queue.
The corresponding get and post requests are then made, and the request results are parsed in the callback.


Volley has its own request queue management mechanism that can control the creation and cancellation of each request. Very convenient and safe.

This makes it possible to control when a request ends at any time, correlate the activity lifecycle, and prevent unnecessary 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 JSON return example: {"ResultCode": "$", "Reason": "Return successd!", "result": {"province": "Zhejiang", "City": "Hangzhou", "AreaCode": "0571", "Z" IP ":" 310000 "," Company ":" China Mobile "," card ":" Mobile Dynamic Zone Card "}}xml return Example: <?xml version=" 1.0 "encoding=" Utf-8 "?>-<root > <resultcode>200</resultcode> <reason>return successd!</reason>-<result&gt          ;           <province> Zhejiang </province> <city> Hangzhou </city> <areacode>0571</areacode> <zip>310000</zip> <company> China Mobile </company> <card> Mobile Zone card </card> </result> </root> * * * 

before using volley, the jar package must be put into the project, and here I write a sample code, as follows:

public class Mainactivity extends Activity implements onclicklistener{//declares a volley request queue private Requestqueue Requestqueue = Null;//get Request Method urlprivate static final String url_get = "http://apis.juhe.cn/mobile/get?phone= 18952201314&AMP;KEY=A53155CC6AF64DAABC66655B060DB56A ";//post request method urlprivate static final String url_post =" http:// Apis.juhe.cn/mobile/get? "; /Current queried mobile number attribution Object Private phoneattribuion phoneattribuion = null; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); SetupViews (); Initvolleyrequest ();} @Overrideprotected void OnStop () {//When the activity interface has been stopped, cancel all network requests Requestqueue.cancelall ("Get_tag"); Requestqueue.cancelall ("Post_tag"); Super.onstop ();} @Overridepublic void OnClick (View v) {int id = v.getid (); switch (ID) {Case r.id.button1://when you click on Volley Get request Volleyge T (); break;case r.id.button2://When you click on the volley Post request Volleypost (); break;default:break;}} private void Setupviews () {Findviewbyid (R.id.buttoN1). Setonclicklistener (This), Findviewbyid (R.id.button2). Setonclicklistener (this);} private void Initvolleyrequest () {//Initialize request queue Requestqueue = Volley.newrequestqueue (This.getapplicationcontext ());} Get request method private void Volleyget () {//New GET request, request result obtained from callback method Onresponse () stringrequest stringrequest = new Stringrequest (Method.get, Url_get, New listener<string> () {@Overridepublic void Onresponse (String arg0) { SYSTEM.OUT.PRINTLN ("Network request succeeded ..."); String result = arg0; SYSTEM.OUT.PRINTLN (result);//Returns the result as JSON format, the following format://{//"ResultCode": "$",//"Reason": "Return successd!",//"result": {"Province": "Jiangsu", "City": "Xuzhou", "AreaCode": "0516", "Zip": "221000", "Company": "China Telecom", "card": "China Telecom Day Wing card"},//"Error_code" ": 0//}//encapsulates the result as an object try {//Converts the result string to a JSON object jsonobject ret = new Jsonobject (result);//Read ResultCode value string resultcode = Ret.getstring ("ResultCode"). Trim (), if ("$". Equals (Result)) {//Request result is normal jsonobject Resultjson = Ret.getjsonobject (" Result ");//Read all property values out of String province = Resultjson.getstring (" province "); String City = rEsultjson.getstring ("City"); String AreaCode = resultjson.getstring ("AreaCode"); String zip = resultjson.getstring ("Zip"); String company = resultjson.getstring ("Company"); String card = resultjson.getstring ("card");//Create a new cell phone attribution object, encapsulate all values in the Phoneattribuion object phoneattribuion = new Phoneattribuion (province, City, Areacode,zip, company, card);//This GET request ends ...} else{//Request Result Exception System.out.println ("Request result exception ...");}} catch (Exception e) {System.out.println (e);}}, New Errorlistener () {@Overridepublic void Onerrorresponse (volleyerror arg0) {System.out.println ("Network request failed ...");}); /Set a TAG property Stringrequest.settag ("Get_tag") for this GET request;//Add this GET request to Requestqueue.add (stringrequest);} private void Volleypost () {//Create a new post request, the request result is obtained from the callback method Onresponse () stringrequest stringrequest = new Stringrequest ( Method.post, Url_post, New listener<string> () {//Override Listener abstract method @overridepublic void Onresponse (String arg0) { SYSTEM.OUT.PRINTLN ("Network request succeeded ..."); String result = arg0; SYSTEM.OUT.PRINTLN (result);//If you need to encapsulate the result as a Phoneattribution object, refer to the Get methodBy the way, you can also extract the method as a business method, call here ...}, new Errorlistener () {//Override Errorlistener abstract method @overridepublic void Onerrorresponse ( Volleyerror arg0) {System.out.println ("Network request failed ...");}) {//Rewrite Stringrequest abstract method @overrideprotected map<string, String> getparams () throws Authfailureerror {Map< String, string> map = new hashmap<string, string> (), Map.put ("Phone", "18952201314"), Map.put ("Key", " A53155CC6AF64DAABC66655B060DB56A "); return map;}};/ /Set a TAG property Stringrequest.settag ("Post_tag") for this GET request;//Add this GET request to Requestqueue.add (stringrequest);}}


The code uses one of its own defined entity class phoneattribution, which reads as follows:

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >//cell phone number attribution to public class Phoneattribuion {private string province;//province private string city;//City private String AreaCode ;    Area code private String zip;   Zip code private String Company; Carrier private String card; Card Package Type public phoneattribuion (String province, String city, String areacode,string Zip, string company, String card) {Supe R (); this.province = province;this.city = City;this.areacode = Areacode;this.zip = Zip;this.company = Company;this.card = C ard;} Public String getprovince () {return province;} public void Setprovince (String province) {this.province = province;} Public String getcity () {return city;} public void Setcity (String city) {this.city = city;} Public String Getareacode () {return areacode;} public void Setareacode (String areacode) {this.areacode = AreaCode;} Public String Getzip () {return zip;} public void Setzip (String zip) {this.zip = zip;} Public String Getcompany () {return company;} public void Setcompany (String company) {This.company = Company;} Public String Getcard () {return card;} public void Setcard (String card) {this.card = card;}} </span>


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

Android Volley Demo

Android's Volley

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.