Android HTTP operation library Volley basic use tutorial

  • 2021-07-10 20:50:56
  • OfStack

Previously, Library built in android was used to connect and operate API by GET, POST, etc.
But recently, I want to find out if there is a good library, which should get twice the result with half the effort.
At the beginning, I found three sets for more people
1.Android Asynchronous Http Client
2.okhttp
square development and open source, because they used their home before picasso, so full of good feeling about this set, but it's a pity that the way of use is not very like
3.Volley
Volley was released by Google in 2013 when Google I/O, and has accumulated high popularity up to now.
GitHub project address of Volley: https://github.com/mcxiaoke/android-volley

Create an Json request
volley comes with JsonObjectRequest and JsonArrayRequest to handle Json object request and Json data request respectively (but voley does not use gson library to write an GsonRequest, send an request, and volley directly returns an java object, but we can write it ourselves).
Create an json object request.
Sending a request is as simple as that, creating an JsonRequest object, writing the response callback interface, and putting the request into the request queue. JsonArrayRequest is similar.


// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
String url = "http://api.androidhive.info/volley/person_object.json";

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,url, null,
      new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
          Log.d(TAG, response.toString());
        }
      }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
          VolleyLog.d(TAG, "Error: " + error.getMessage());
        }
      });

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

Create an String request
StringRequest can be used to request data of any string type: json, xml, text, and so on.


// Tag used to cancel the request
String 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 queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

Create an POST request
All the above are GET requests, and the following is POST request. Different from GET request, it is only necessary to change the request type to POST request when creating the request, and the getParams method of override Request can be used.


// Tag used to cancel the request
String 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 queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

Add request header information


// Tag used to cancel the request
String 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 queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

Create an Image request
The Volley library comes with the NetworkImageView class. This ImageView can automatically download pictures using volley
1. Load pictures with NetworkImageView
First, explain the principle of loading pictures under 1:
NetworkImageView loading pictures requires 1 ImageLoader and 1 picture URL, and this ImageLoader object requires 1 request queue object and ImageCahe object. After calling the setUrl method of NetworkImageView, it will first judge whether the URL of the current ImageView and the newly incoming URL are identical. If they are the same, there is no need to send the http request. If they are different, then the ImageLoader object is used to send the http request to obtain pictures.


ImageLoader imageLoader = AppController.getInstance().getImageLoader();
// If you are using NetworkImageView
imgNetWorkView.setImageUrl(Const.URL_IMAGE, imageLoader);

Loading a picture is as simple as that ~ ~ ~
2. Load pictures with ImageView
This process is similar to NetworkImageView


ImageLoader imageLoader = AppController.getInstance().getImageLoader();

// If you are using normal ImageView
imageLoader.get(Const.URL_IMAGE, new ImageListener() {

  @Override
  public void onErrorResponse(VolleyError error) {
    Log.e(TAG, "Image Load Error: " + error.getMessage());
  }

  @Override
  public void onResponse(ImageContainer response, boolean arg1) {
    if (response.getBitmap() != null) {
      // load image into imageview
      imageView.setImageBitmap(response.getBitmap());
    }
  }
});

It can be one more simple point:


// Loading image with placeholder and error image
imageLoader.get(Const.URL_IMAGE, ImageLoader.getImageListener(imageView, R.drawable.ico_loading, R.drawable.ico_error));


A default ImageListener has been written in ImageLoader. getImageListener method
Volley Cache
volley comes with a powerful cache mechanism to manage requests to cache, which will reduce the number of network requests and user waiting time.
Load the request from the request Cache:


Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(url);
if(entry != null){
  try {
    String data = new String(entry.data, "UTF-8");
    // handle data, like converting it to xml, json, bitmap etc.,
  } catch (UnsupportedEncodingException e) {   
    e.printStackTrace();
    }
  }
}else{
  // Cached response doesn't exists. Make network call here
}

Invalidate the request cache
Failure does not mean deletion, and Volley continues to use cached objects until new data is retrieved from the server, which overwrites the old data.


AppController.getInstance().getRequestQueue().getCache().invalidate(url, true);

Turn off Cache
If you want to turn off the Cache function of a 1 request, just call the setShouldCache () method of Request:


// String request
StringRequest stringReq = new StringRequest(....);

// disable cache
stringReq.setShouldCache(false);

Delete Cache of a 1URL
Calling the remove method of Cache removes the cache of this URL:


// Tag used to cancel the request
String 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 queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

0

Delete all Cache


// Tag used to cancel the request
String 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 queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

1

Cancel a request
When you add a request to the request queue, you can find that the addToRequestQueue (request, tag) method also accepts an tag parameter, which is used to mark a Class 1 request, so that all requests of this tag can be cancelled:


// Tag used to cancel the request
String 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 queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

2

Request priority
When creating an request, the getPriority method of Override Request method can return a priority, which is divided into Normal, Low, Immediate and High.


private 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;
    }

  };


Related articles: