Android working with Volley Library

Source: Internet
Author: User

Volley provides a beautiful framework that makes network access for Android applications easier and faster. Volley abstracts and implements the underlying HTTP Client library, so that you don't pay attention to HTTP Client details and focus on writing more beautiful and clean RESTful HTTP requests. In addition, Volley requests are executed asynchronously without blocking the main thread.

Features provided by Volley

In short, the following main functions are provided:

1. encapsulated asynchronous RESTful request API;

2. An elegant and robust Request queue;

3. A scalable architecture that enables developers to implement custom request and response processing mechanisms;

4. Use the external HTTP Client library;

5. Cache Policy;

6. Custom network image loading views (NetworkImageView, ImageLoader, etc );

 

Why do I use Asynchronous HTTP requests?

Android requires asynchronous execution of HTTP requests. If an HTTP request is executed in the main thread, the android. OS. NetworkOnMainThreadException may be thrown. Blocking the main thread has some serious consequences. It hinders UI rendering and the user experience is Not smooth, which may lead to terrible ANR (Application Not Responding ). To avoid these traps, as a developer, we should always ensure that the HTTP request is in a different thread.

 

How to Use Volley

This blog will detail how to use volley in the application process. It will include the following aspects:

1. install and use the Volley Library

2. Use Request queue

3. asynchronous JSON and String requests

4. Cancel the request

5. retry failed requests. custom request timeout

6. Set the Request Header (HTTP headers)

7. Use Cookies

8. handle errors

Install and use the Volley Library

Introducing Volley is very simple. First, clone it from the git Library:

git clone https://android.googlesource.com/platform/frameworks/volley

Compile it as a jar package, and put the jar package in the libs directory of your project.

Creating Volley Singleton class
import info.androidhive.volleyexamples.volley.utils.LruBitmapCache;import android.app.Application;import android.text.TextUtils; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.toolbox.ImageLoader;import com.android.volley.toolbox.Volley; public class AppController extends Application {     public static final String TAG = AppController.class            .getSimpleName();     private RequestQueue mRequestQueue;    private ImageLoader mImageLoader;     private static AppController mInstance;     @Override    public void onCreate() {        super.onCreate();        mInstance = this;    }     public static synchronized AppController getInstance() {        return mInstance;    }     public RequestQueue getRequestQueue() {        if (mRequestQueue == null) {            mRequestQueue = Volley.newRequestQueue(getApplicationContext());        }         return mRequestQueue;    }     public ImageLoader getImageLoader() {        getRequestQueue();        if (mImageLoader == null) {            mImageLoader = new ImageLoader(this.mRequestQueue,                    new LruBitmapCache());        }        return this.mImageLoader;    }     public <T> void addToRequestQueue(Request<T> req, String tag) {        // set the default tag if tag is empty        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);        getRequestQueue().add(req);    }     public <T> void addToRequestQueue(Request<T> req) {        req.setTag(TAG);        getRequestQueue().add(req);    }     public void cancelPendingRequests(Object tag) {        if (mRequestQueue != null) {            mRequestQueue.cancelAll(tag);        }    }}

 

 

1. Making json object request

String url = "";         ProgressDialog pDialog = new ProgressDialog(this);pDialog.setMessage("Loading...");pDialog.show();                      JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,                url, null,                new Response.Listener<JSONObject>() {                     @Override                    public void onResponse(JSONObject response) {                        Log.d(TAG, response.toString());                        pDialog.hide();                    }                }, new Response.ErrorListener() {                     @Override                    public void onErrorResponse(VolleyError error) {                        VolleyLog.d(TAG, "Error: " + error.getMessage());                        // hide the progress dialog                        pDialog.hide();                    }                }); // Adding request to request queueAppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

 

2. Making json array request

// Tag used to cancel the requestString tag_json_arry = "json_array_req"; String url = "http://api.androidhive.info/volley/person_array.json";         ProgressDialog pDialog = new ProgressDialog(this);pDialog.setMessage("Loading...");pDialog.show();              JsonArrayRequest req = new JsonArrayRequest(url,                new Response.Listener<JSONArray>() {                    @Override                    public void onResponse(JSONArray response) {                        Log.d(TAG, response.toString());                                pDialog.hide();                                 }                }, new Response.ErrorListener() {                    @Override                    public void onErrorResponse(VolleyError error) {                        VolleyLog.d(TAG, "Error: " + error.getMessage());                        pDialog.hide();                    }                }); // Adding request to request queueAppController.getInstance().addToRequestQueue(req, tag_json_arry);

 

3. Making String request

// Tag used to cancel the requestString  tag_string_req = "string_req"; String url = "http://api.androidhive.info/volley/string_response.html";         ProgressDialog pDialog = new ProgressDialog(this);pDialog.setMessage("Loading...");pDialog.show();              StringRequest strReq = new StringRequest(Method.GET,                url, new Response.Listener<String>() {                     @Override                    public void onResponse(String response) {                        Log.d(TAG, response.toString());                        pDialog.hide();                     }                }, new Response.ErrorListener() {                     @Override                    public void onErrorResponse(VolleyError error) {                        VolleyLog.d(TAG, "Error: " + error.getMessage());                        pDialog.hide();                    }                }); // Adding request to request queueAppController.getInstance().addToRequestQueue(strReq, tag_string_req);

 

4. Adding post parameters

// Tag used to cancel the requestString tag_json_obj = "json_obj_req"; String url = "http://api.androidhive.info/volley/person_object.json";         ProgressDialog pDialog = new ProgressDialog(this);pDialog.setMessage("Loading...");pDialog.show();                      JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,                url, null,                new Response.Listener<JSONObject>() {                     @Override                    public void onResponse(JSONObject response) {                        Log.d(TAG, response.toString());                        pDialog.hide();                    }                }, new Response.ErrorListener() {                     @Override                    public void onErrorResponse(VolleyError error) {                        VolleyLog.d(TAG, "Error: " + error.getMessage());                        pDialog.hide();                    }                }) {             @Override            protected Map<String, String> getParams() {                Map<String, String> params = new HashMap<String, String>();                params.put("name", "Androidhive");                params.put("email", "abc@androidhive.info");                params.put("password", "password123");                 return params;            }         }; // Adding request to request queueAppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

 

5. Adding request headers

// Tag used to cancel the requestString tag_json_obj = "json_obj_req"; String url = "http://api.androidhive.info/volley/person_object.json";         ProgressDialog pDialog = new ProgressDialog(this);pDialog.setMessage("Loading...");pDialog.show();                      JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,                url, null,                new Response.Listener<JSONObject>() {                     @Override                    public void onResponse(JSONObject response) {                        Log.d(TAG, response.toString());                        pDialog.hide();                    }                }, new Response.ErrorListener() {                     @Override                    public void onErrorResponse(VolleyError error) {                        VolleyLog.d(TAG, "Error: " + error.getMessage());                        pDialog.hide();                    }                }) {             /**             * Passing some request headers             * */            @Override            public Map<String, String> getHeaders() throws AuthFailureError {                HashMap<String, String> headers = new HashMap<String, String>();                headers.put("Content-Type", "application/json");                headers.put("apiKey", "xxxxxxxxxxxxxxx");                return headers;            }         }; // Adding request to request queueAppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

 

 

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.