Android custom and uses the Volley framework to request the network, and Android volley

Source: Internet
Author: User

Android custom and uses the Volley framework to request the network, and Android volley

Hello everyone, today we will talk about how to use the Volley framework to request the network and why to use the Volley framework. Here we will first talk about the advantages of using the Volley framework to request the network. volley is easy to customize, that is, you can set the volley framework as needed, and the volley framework supports Request priority settings, that is, you can set the priority of network requests, in addition, volley Framework requests support canceling one or more requests. This will be explained in the future when setting requests, and it can automatically schedule network requests, as for other scenarios such as code robustness and multi-concurrency support, we will not list them one by one. Here we will introduce how to customize and use the Volley framework:

Step 1: Define the netrequest class to inherit the StringRequest class

1. In this class, you must first define three global variables,

 

1 private Priority priority; 2 private Map <String, String> headers; 3 private Map <String, String> params; 4 5/** 6 * initialize the global variable 7 */8 private void init () {9 priority = Priority. NORMAL; 10 headers = new HashMap <> (); 11 params = new HashMap <> (); 12}

 

2. Implement two constructor methods. In these two constructor methods, you only need to initialize the custom three global variables.

1 public NetRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {2 super(method, url, listener, errorListener);3         init();4     }5 6 public NetRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {7 super(url, listener, errorListener);8         init();9     }

3. override the priority setting method.

1 // set Priority 2 @ Override3 public priority getPriority () {4 return Priority; 5}

4. Rewrite the method for adding request header information to a request

1 // method 2 @ Override 3 public Map <String, String> getHeaders () throws AuthFailureError {4 return headers; 5} 6 7 @ Override 8 public Map <String, String> getParams () throws AuthFailureError {9 return params; 10} 11 12 public NetRequest setPriority (Priority priority) {13 this. priority = priority; 14 return this; 15} 16 17 public NetRequest addRequestHeader (String key, String value) {18 this. headers. put (key, value); 19 return this; 20} 21 22 public NetRequest addParams (String key, String value) {23 this. params. put (key, value); 24 return this; 25}

 

5. Customize a request sending method. The VolleyUtil class is a tool class. The next step is to define it.

1/** 2 * Send request 3 */4 public void start () {5 VolleyUtil. start (this); 6}

6. Customize a static class Builder to pass Parameters for network requests. This is also called the constructor mode.

1 // constructor Mode 2 public static class Builder {3 4 private String url; 5 private int method; 6 private CallBack callBack; 7 8 public Builder setCallBack (CallBack callBack) {9 this. callBack = callBack; 10 return this; 11} 12 public Builder setUrl (String url) {13 this. url = url; 14 return this; 15} 16 public Builder setMethod (int method) {17 this. method = method; 18 return this; 19}
20}

7. Customize a buileder method to request the network to return NetRequest (this step is critical)

1/** 2 * Create a NetRequest request network 3 * @ return NetRequest 4 */5 public NetRequest build () {6 NetRequest nr = new NetRequest (7 method, 8 url, 9 new Response. listener <String> () {10 @ Override11 public void onResponse (String response) {12 if (callBack! = Null) {13 callBack. onSuccess (response); 14} 15} 16}, 17 new Response. errorListener () {18 @ Override19 public void onErrorResponse (VolleyError error) {20 if (callBack! = Null) {21 callBack. onError (error); 22} 23} 24}); 25 return nr; 26}

8. Defining an interface Callback contains two abstract methods to implement the last two of the four parameters of the request network (because the network request is a one-step operation, therefore, you need to customize a class to implement this excuse and rewrite the two methods in the interface)

1 import com.android.volley.VolleyError;2 3     /**4      * Created by zhangdi on 2016/8/8.5      */6     public interface CallBack {7         public void onSuccess(String respone);8         public void onError(VolleyError error);9     }    

Step 2: Customize a tool class (that is, the tool class in the start method in step 1, and the methods in it are set to static for convenient calling, which is also a type of factory Mode)

1. initialize the Request queue first.

1 private static RequestQueue requestQueue; 2/*** 3 * initialize the Request queue 4 * @ param mContext 5 */6 public static void init (Context mContext) {7 if (requestQueue = null) {8 requestQueue = Volley. newRequestQueue (mContext); 9} 10}

2. Set the get Request Method

1/** 2 * get request 3 * @ param url 4 * @ return 5 */6 public static NetRequest. builder get (String url) {7 return new NetRequest. builder () 8. setMethod (Request. method. GET) 9. setUrl (url); 10}

3. Set the post Request Method

1/** 2 * post request 3 * @ return4 */5 public static NetRequest. builder post (String url) {6 return new NetRequest. builder () 7. setMethod (Request. method. POST) 8. setUrl (url); 9}

4. Define to start running the start method (add requests to the Request queue)

1/** 2 * add the request to the Request queue 3 */4 public static void start (NetRequest nr) {5 requestQueue. add (nr); 6}

5. Set the method for canceling a request (Use method overload to cancel or cancel a group)

1 // method overload 2 public static void cancel (Object tag) {3 requestQueue. cancelAll (tag); 4} 5 6 public static void cancel (RequestQueue. requestFilter filter) {7 requestQueue. cancelAll (filter); 8}

Here the cancel () method the first method to cancel a request is to cancel all requests, the second method to cancel a request is to customize the selective cancellation of a request

Step 3: Call the encapsulated static class to implement the request network

<1> first, let's talk about using get to request the network.

1. Define an internal class, that is, network Callback, implement the Callback interface, and override the two methods. I have already explained how to rewrite them in the code block. Read carefully.

1 private class NetCallBack1 implements CallBack {2 @ Override 3 public void onSuccess (String respone) {4 here the request is successful and the operation is executed. 5 remember that all network requests are asynchronous, therefore, the function of loading the data update interface must be implemented here 6 or a null pointer error will be reported 7} 8 9 @ Override10 public void onError (VolleyError error) {11 here is the operation performed after the network request fails. 12} 13}

2. Request network using factory Mode

1 VolleyUtil. get (network interface you requested) 2. setCallBack (new NetCallBack () // This is the callback function customized in the previous step 3. build () 4. setPriority (Request. priority. HIGH) 5. addRequestHeader ("apikey", "Your Own apiley") 6. start ();

<2> How to Use post requests

I implemented the callback interface directly during the call.

1 VolleyUtil. post ("http: // 192.168.191.1: 8080/Server/doReg. jsp ") 2. setCallBack (new CallBack () {3 @ Override 4 public void onSuccess (String respone) {5 successful requests are executed step 6} 7 8 @ Override 9 public void onError (VolleyError error) {10 steps 11} 12} when the request fails) 13. build () 14. addParams ("name", "Zhang San") 15. addParams ("pwd", "12345678") 16. setTag ("post") 17. start ();

The addParams method has a special definition in step 2 NetRequest. The code can be found in step 1.

Now, even if you have completed the process of using the volley framework to request the network, it seems complicated to define, but this is a permanent one. You only need to define it once in the project, you can directly call a network request in the project, note that you also need to set the request permissions for network requests (if you do not know how to set them, you can find them in the article I wrote about location). This must be stated in the list file, also, if you want to initialize the tool class VolleyUtil once and for all, this code can be placed in the global class, that is, the Application class. The Code is as follows:

1/** 2 * Created by zhangdi on 2016/8/23. 3 */4 public class MyApplication extends Application {5 6 @ Override 7 public void onCreate () {8 super. onCreate (); 9 VolleyUtil. init (this); // initialize the Request queue 10} 11 12}

All right, even if all the steps for customizing and using the Volley framework to request network data are completed, of course there are many network request frameworks, and Volley is not the best, however, the advantages of the Volley framework are also obvious. Therefore, the Volley framework is more advantageous for lightweight request network data. If you feel that this article is not bad, please recommend it. If there are any incorrect summary or incorrect knowledge points, Please comment and correct them. Thank you.

 

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.