Volley of Android

Source: Internet
Author: User

Volley of Android

Introduction:

Volley is a network communication library officially released by Google on Google I/O 2013 on the Android platform.
For previous network requests, complicated issues such as enabling threads, memory leaks, and performance should be considered. However, the Volley framework has helped us solve these problems and provided a complete request API. We only need to use it as required.

 

Features:

Faster, simpler, and more robust network communication
Efficient asynchronous processing of Get and Post network requests and network images
Allows you to sort network requests by priority.
Cache of network requests
Multi-level cancellation request
Interaction with Activity lifecycle (canceling all network requests at Activity end)
Using Volley can simplify the development of some network communication. Of course, Volley is not suitable for the network requests of big data (large payloads) and streaming media. For example, download files and videos of hundreds of megabytes.
Volley is open-source and can be customized or directly used as a Jar package.

 

Usage:

Use of Volley's Get and Post request methods
Volley's network Request queue establishes and cancels queue requests


To create a request, first create a queue and add the request to the Request queue.
Then perform the corresponding Get and Post requests, and obtain the resolution of the Request results in the callback.

 

Volley has its own request queue management mechanism to control the creation and cancellation of each request. Very convenient and secure.

In this way, you can control at any time when a request ends and the Activity lifecycle is associated to prevent unnecessary requests.

 

Example:

First, we need to select a Network Service API. Here I select the mobile phone in the aggregated data to query the API, 1 register 2 application, and after the application, an AppKey will be assigned to your application, the following is an API description:

 

/*** Interface address: response? Phone = 13429667914 & key = the KEY request parameters you applied: the name type is required. phoneint is the mobile phone number to be queried, or the first seven keystrings of the mobile phone number are the application APPKEY (application details page query) dtypestring. No data is returned in xml or json format, default json call example and debugging 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 code companystring carrier cardstring card type JSON return example: {resultcode: 200, reason: return Successd !, Result: {province: Zhejiang, city: Hangzhou, areacode: 0571, zip: 310000, company: China Mobile, card: Mobile dynamic zone card} XML return example:
 -
       
  
   
200
         
  
   
Return Successd!
  -
            
   
    
Zhejiang
              
   
    
Hangzhou
   0571           
   
    
310000
              
   
    
China Mobile
              
   
    
Mobile dynamic zone card
          
    
 **/

Before using Volley, you must put the jar package into the project. Here I write an example code, as shown below:

 

 

Public class MainActivity extends Activity implements OnClickListener {// declare 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 & key = a53155cc6af64daabc66655b060db56a; // URLprivate static final String URL_POST = http://apis.juhe.cn/mobile/geta ?; // The currently queried mobile phone number is the 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 stopped, cancel all network request 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 Volley Get Request, volleyGet (); break; case R. id. button2: // when you click 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 () {// create a get request. The request result is returned from the callback method onResponse () stringRequest stringRequest = new StringRequest (Method. GET, URL_GET, new Listener
 
  
() {@ Overridepublic void onResponse (String arg0) {System. out. println (Network request successful ...); string result = arg0; System. out. println (result); // The returned result is in json format, as follows: // {// resultcode: 200, // reason: Return Successd !, // Result: {province: Jiangsu, city: Xuzhou, areacode: 0516, zip: 221000, company: China Telecom, card: China Telecom Tianyi card}, // error_code: 0 //} // encapsulate the result as the object try {// convert the result String to the Json object JSONObject ret = new JSONObject (result ); // read the resultcode value String resultCode = ret. getString (resultcode ). trim (); if (200. equals (result) {// The request result is normal. JSONObject resultJson = ret. getJSONObject (result); // read all attribute values. 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 mobile phone attribution object, encapsulate all values in the phoneAttribuion object to phoneAttribuion = new PhoneAttribuion (province, city, areaCode, zip, company, card ); // The Get request ends now ...} else {// The request result is abnormal. System. out. println (the request result is abnormal ...);}} catch (Exception e) {System. out. println (e) ;}}, new ErrorListener () {@ Overridepublic void onErrorResponse (VolleyError arg0) {System. out. println (Network request failed ...);}}); // set a Tag attribute stringRequest for this get request. setTag (GET_TAG); // Add this get request to requestQueue. add (stringRequest);} private void volleyPost () {// create a post request. Obtain the StringRequest stringRequest = new StringRequest (Method. POST, URL_POST, new Listener
  
   
() {// Override the abstract method of Listener @ Overridepublic void onResponse (String arg0) {System. out. println (Network request successful ...); string result = arg0; System. out. println (result); // If You Need to encapsulate the result as a PhoneAttribution object, you can refer to the method in the Get method or extract the method as a business method, call...} here ...}}, new ErrorListener () {// override the abstract method of ErrorListener @ Overridepublic void onErrorResponse (VolleyError arg0) {System. out. println (Network request failed ...);}}) {// rewrite StringRequest's abstract method @ Overrideprotected Map
   
    
GetParams () throws AuthFailureError {Map
    
     
Map = new HashMap
     
      
(); Map. put (phone, 18952201314); map. put (key, a53155cc6af64daabc66655b060db56a); return map ;}; // set a Tag attribute stringRequest for this get request. setTag (POST_TAG); // Add this get request to requestQueue. add (stringRequest );}}
     
    
   
  
 


 

The Code uses a Defined Object Class PhoneAttribution. The content is as follows:

 

// Mobile phone number attribution class public class PhoneAttribuion {private String province; // province private String city; // city private String areaCode; // region 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) {super (); this. province = province; this. city = city; this. areaCode = areacode=this.zip = zip; this. company = company; this. card = card;} 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) Export 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 ;}}

 

 

 

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.