Android Volley framework (2), androidvolley
In the previous article, I introducedvolleyThe features of the frameworkvolley.jarIntroduce our project and the two most common classes in the volley frameworkRequestQueue RequestBasic usage; this introductionVolleySome of the more common knowledge points in use;
We recommend that you first read the previous article: Use of Android Volley (1)
The article structure is as follows:
Use Request queue RequestQueue
Requests in Volley must be added to RequestQueue for execution. Therefore, you must first create a RequestQueue
RequestQueue reqQueue = Volley. newRequestQueue (this); // this indicates the Context object
Generally, a unified request queue needs to be managed in an application.Singleton Mode(Note: This is not necessary, but it has many advantages to use this method ~), That is, an Application object is held in the entire Application.ApplicationAnd initialize it in this class.RequestQueueAnd other core objects, as well as some of the methods we need to implement;
Public class ApplicationController extends Application {// create a TAG to facilitate debugging or Log private static final String TAG = getApplication (). getSimpleName (); // create a global Request queue private RequestQueue reqQueue; // create a static ApplicationController object for global access to private static ApplicationController mInstance; @ Override public void onCreate () {super. onCreate (); // initialize mInstance = this;}/*** the following are the methods for adding and canceling requests that require our own encapsulation * // return an Applicatio NController Singleton private static synchroized ApplicationController getInstance () {return mInstance;} // returns the global RequestQueue object. If it is null, create it public RequestQueue getRequestQueue () {if (reqQueue = null) reqQueue = Volley. newRequestQueue (getApplicationContext); return reqQueue;}/*** Add the Request object to RequestQueue. Because the Request has * StringRequest, JsonObjectResquest... * generic type is required. At the same time, the * tag can be used as an optional parameter to mark every different Request */public <T> void addToRequestQueue (Request <T> req, String tag) {// If the tag is empty, the default TAG req is used. setTag (TextUtils. isEmpty (tag )? TAG: tag); getRequestQueue (). add (req);} public <T> void addToRequestQueue (Request <T> req) {req. setTag (TAG); getRequestQueue (). add (req);} // cancel the Request public void cancelPendingRequests (Object Tag) {if (reqQueue! = Null) {reqQueue. cancelAll (tag );}}}
Tips:After implementing our Application class, we needManifest.xmlModifying
<application android:name=".ApplicationController" ....>
Execute asynchronous request
As mentioned in the previous article, Volley mainly provides the following types of asynchronous requests:
- JsonObjectRequest is used to receive and send data of the JsonObject type.
- JsonArrayRequest is used to receive and send data of the JsonArray type.
- StringRequest is used to receive and send data whose response body is String.
JsonObjectRequest
This is a message for sending and receivingJSONThe most common data class. Some methods in this class can be used to send (GET, POST, DELETE, PUT) and other appropriate HTTP requests. Common operation code example:
Final String url = "http://www.jycoder.com/person.json"; JsonObjectRequest req = new JsonObjectRequest (url, null, new Response. listener <JsonObject> () {@ Override public void onResponse (JsonObject response) {// calls back this function when the response is correct}, new ResponseError. listener () {@ Override public void onErrorResponse (VolleyError error) {// callback this function when an incorrect response}); // Add the request to the Global RequestQueueApplicationController. getInstance (). addToRequestQueue (req );
To send an HTTP request (Post Put Get Delete) Request:
If you want to send a Post or Delete request, you can useJsonObjectTo achieve
// Save the post parameter HashMap <String, String> params = new HashMap <String, String> (); params. put ("userId", "123189283"); // new JsonObject (params) as the JsonObjectRequest parameter JsonObjectRequest req = new JsonObjectRequest (url, new JsonObject (params), new Response. listener <JsonObject> (){...}, new Response. errorListener (){...});
SendJsonArrayRequest StringRequestAndJsonObjectRequestSimilar:
JsonArrayRequest req=new JsonArrayRequest(url, new Response.Listener<JsonArray>(){..}, new Response.ErrorListener(){..});StringRequest req=new StringRequest(url, new Response.Listener<String>(){..}, new Response.ErrorListener(){..});
Cancel Request
The Volley framework provides powerful APIs to cancel one or more pending or running requests.setTag()Method? The Tag is used to mark each Request. We can use this Tag to cancel the Request.
// You can use the setTag method to add tagreq for each Request. setTag ("My Tag"); // You can also set ApplicationController when we add it to RequestQueue. getInstance (). addToRequestQueue (req, "My Tag"); // cancel RequestreqQueue. cancelAll ("My Tag"); // or the previous implementation method ApplicationController. getInstance (). cancelPendingRequests ("My Tag ");
Tips:After learning the above three aspects, we have mastered the most common Volley methods. If you want to make your application more robust, you also need to understand the error handling in Volley, set the retry and timeout mechanisms for request failures, set the request priority, and set the request header.
Extended Part
Retry upon request failure and custom request timeout
Volley provides a scheme that can be called through the Request object.setRetryPolicy()Method, set timeout and retry request
Request. setRetryPolicy (new DefaultRetryPolicy (20 *, 1, 1.0f);/** DefaultRetryPolicy (int, int, float); the first one indicates the timeout time, that is, if the timeout value exceeds 20 s, the third parameter indicates the maximum number of retries. If this parameter is set to 1.0f, the system does not retry if the request times out */
Set Request priority
In actual development, we often need to increase the priority of some requests for priority execution. You can override the getPrioriity () method,
// The priorities include LOW, NORMAL, HIGH, and IMMEDIATEprivate Priority priority = Priority. HIGH; StringRequest strReq = new StringRequest (Method. GET, Const. URL_STRING_REQ, new Response. listener <String> () {@ Override public void onResponse (String response) {Log. d (TAG, response. toString (); msgResponse. setText (response. toString (); hideProgressDialog () ;}}, new Response. errorListener () {@ Override public void onErrorResponse (VolleyError error) {VolleyLog. d (TAG, "Error:" + error. getMessage (); hideProgressDialog () ;}}) {@ Override public Priority getPriority () {return priority ;}};
Set the Request Header (HTTP header)
In many cases, you need to add headers for HTTP requests. A typical scenario is basic HTTP Authorization authentication. The Request class providesgetHeaders()Method, You need to overwrite and add your own custom Header
@Overridepublic Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("CUSTOM_HEADER", "Yahoo"); headers.put("ANOTHER_CUSTOM_HEADER", "Google"); return headers;}
Error Handling
You may have noticed that when creating a Request object, the constructor parameters includenew Response.ErrorListener()This is typical error handling.
Volley has the following types of errors:
- AuthFailureError-Basic Http identity authentication (authorization) error.
- NetworkError-network error
- NoConnectionError-network connection error.
- ParseError-data parsing error.
- ServerError-server error.
- TimeoutError-timeout error.
You can implement your own error handling class to return specific error messages.
Public class VolleyErrorHelper {// is used to return specific error information and distinguish the error category public static String getMessage (Object error, Context context) {if (error instanceof TimeoutError) {return context. getResources (). getString (R. string. generic_server_down);} else if (isServerProblem (error) {return handleServerError (error, context);} else if (isNetworkProblem (error) {return context. getResources (). getString (R. string. no_internet );} Return context. getResources (). getString (R. string. generic_error);} // determines whether the error is a network error. private static boolean isNetworkProblem (Object error) {return (error instanceof NetworkError) | (error instanceof NoConnectionError );} // determine whether the server-side error is private static boolean isServerProblem (Object error) {return (error instanceof ServerError) | (error instanceof AuthFailureError);} // process the server-side error private static Strin G handleServerError (Object err, Context context) {VolleyError error = (VolleyError) err; NetworkResponse response = error. networkResponse; if (response! = Null) {switch (response. statusCode) {case 404: case 422: case 401: try {// server might return error like this {"error ": "Some error occured"} // Use "Gson" to parse the result HashMap <String, String> result = new Gson (). fromJson (new String (response. data), new TypeToken <Map <String, String >> (){}. getType (); if (result! = Null & result. containsKey ("error") {return result. get ("error") ;}} catch (Exception e) {e. printStackTrace ();} return error. getMessage (); default: return context. getResources (). getString (R. string. generic_server_down) ;}} return context. getResources (). getString (R. string. generic_error );}}
Summary:
To sum up, we have basically completed most of the Volley Framework's knowledge. The only thing that is not involved and important isImage CacheThe content will be introduced in the next blog. Remember to pay attention to personal Weibo and public platforms,
Reference: Asynchronous HTTP Requests in Android Using Volley