In the past, we used the library built-in Android to connect and operate APIs, such as GET, POST, etc.
But recently I want to find out if there is any useful library, which should be twice the result with half the effort.
I found three sets that were used by many people.
Asynchronous Http Client
Square is developed and open source. Because I have used their picasso before, I have a good impression of this set, but I am sorry I don't like it very much.
Volley was released by Google during Google I/O in 2013, and has accumulated a lot of popularity.
Volley's GitHub project address: /mcxiaoke/android-volley
Create a Json request
Volley comes with JsonObjectRequest and JsonArrayRequest to handle Json object requests and Json data requests respectively (but Volley does not use the gson library to write a GsonRequest, send a request, and Volley directly returns a java object, but we can write it ourselves).
Create a json object request.
Sending a request is as simple as this, just create a JsonRequest object, write the response callback interface, and put the request into the request queue. JsonArrayRequest is similar.
// Tag used to cancel the request String tag_json_obj = "json_obj_req"; String url = "/volley/person_object.json"; JsonObjectRequest jsonObjReq = new JsonObjectRequest(,url, null, new <JSONObject>() { @Override public void onResponse(JSONObject response) { (TAG, ()); } }, new () { @Override public void onErrorResponse(VolleyError error) { (TAG, "Error: " + ()); } }); // Adding request to request queue ().addToRequestQueue(jsonObjReq, tag_json_obj);
Create a String request
StringRequest can be used to request data of any string type: json, xml, text, etc.
// Tag used to cancel the request String tag_string_req = "string_req"; String url = "/volley/string_response.html"; ProgressDialog pDialog = new ProgressDialog(this); ("Loading..."); (); StringRequest strReq = new StringRequest(, url, new <String>() { @Override public void onResponse(String response) { (TAG, ()); (); } }, new () { @Override public void onErrorResponse(VolleyError error) { (TAG, "Error: " + ()); (); } }); // Adding request to request queue ().addToRequestQueue(strReq, tag_string_req);
Create a POST request
All the above mentioned GET requests are GET requests. Let’s talk about POST requests. Unlike GET requests, just change the request type to POST request when creating the request, and override the getParams method of the Request.
// Tag used to cancel the request String tag_json_obj = "json_obj_req"; String url = "/volley/person_object.json"; ProgressDialog pDialog = new ProgressDialog(this); ("Loading..."); (); JsonObjectRequest jsonObjReq = new JsonObjectRequest(, url, null, new <JSONObject>() { @Override public void onResponse(JSONObject response) { (TAG, ()); (); } }, new () { @Override public void onErrorResponse(VolleyError error) { (TAG, "Error: " + ()); (); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); ("name", "Androidhive"); ("email", "abc@"); ("password", "password123"); return params; } }; // Adding request to request queue ().addToRequestQueue(jsonObjReq, tag_json_obj);
Add request header information
// Tag used to cancel the request String tag_json_obj = "json_obj_req"; String url = "/volley/person_object.json"; ProgressDialog pDialog = new ProgressDialog(this); ("Loading..."); (); JsonObjectRequest jsonObjReq = new JsonObjectRequest(,url, null,new <JSONObject>() { @Override public void onResponse(JSONObject response) { (TAG, ()); (); } }, new () { @Override public void onErrorResponse(VolleyError error) { (TAG, "Error: " + ()); (); } }) { /** * Passing some request headers * */ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); ("Content-Type", "application/json"); ("apiKey", "xxxxxxxxxxxxxxx"); return headers; } }; // Adding request to request queue ().addToRequestQueue(jsonObjReq, tag_json_obj);
Create Image Request
The Volley library comes with the NetworkImageView class. This ImageView can automatically download images using volley.
1. Use NetworkImageView to load images
First, let me explain the principle of loading pictures:
NetworkImageView requires an ImageLoader and an Image URL to load images. This ImageLoader object requires a request queue object and an ImageCahe object. After calling the setUrl method of NetworkImageView, it will first determine whether the current ImageView URL and the newly passed URL are the same. If the same, you no longer need to send an http request. If it is different, then use the ImageLoader object to send an http request to get the image.
ImageLoader imageLoader = ().getImageLoader(); // If you are using NetworkImageView (Const.URL_IMAGE, imageLoader);
Loading an image is that simple~~~
2. Use ImageView to load images
This process is similar to NetworkImageView
ImageLoader imageLoader = ().getImageLoader(); // If you are using normal ImageView (Const.URL_IMAGE, new ImageListener() { @Override public void onErrorResponse(VolleyError error) { (TAG, "Image Load Error: " + ()); } @Override public void onResponse(ImageContainer response, boolean arg1) { if (() != null) { // load image into imageview (()); } } });
It can be simpler:
// Loading image with placeholder and error image (Const.URL_IMAGE, (imageView, .ico_loading, .ico_error));
A default ImageListener has been written in the method
Volley Cache
Volley comes with a powerful cache mechanism to manage request cache, which will reduce the number of network requests and user waiting time.
Load the request from the request cache:
Cache cache = ().getRequestQueue().getCache(); Entry entry = (url); if(entry != null){ try { String data = new String(, "UTF-8"); // handle data, like converting it to xml, json, bitmap etc., } catch (UnsupportedEncodingException e) { (); } } }else{ // Cached response doesn't exists. Make network call here }
Invalidate request cache
Failure does not mean that this is deleted. Volley will continue to use the cached object until new data is obtained from the server, and the new data will overwrite the old data.
().getRequestQueue().getCache().invalidate(url, true);
Close Cache
If you want to turn off the Cache function of a request, you can just call the setShouldCache() method of Request:
// String request StringRequest stringReq = new StringRequest(....); // disable cache (false);
Delete the cache of a URL
Calling the remove method of Cache can delete the cache of this URL:
().getRequestQueue().getCache().remove(url);
Delete all Caches
().getRequestQueue().getCache().clear();
Cancel request
When you add a request to the request queue, you can find that the addToRequestQueue(request, tag) method also accepts a tag parameter, which is used to mark a certain type of request, so that all requests for this tag can be cancelled:
String tag_json_arry = "json_req"; ().getRequestQueue().cancelAll("feed_request");
Request priority
When creating a request, the getPriority method of the Override Request method can return a priority, which is divided into: Normal, Low, Immediate, High.
private Priority priority = ; StringRequest strReq = new StringRequest(, Const.URL_STRING_REQ, new <String>() { @Override public void onResponse(String response) { (TAG, ()); (()); hideProgressDialog(); } }, new () { @Override public void onErrorResponse(VolleyError error) { (TAG, "Error: " + ()); hideProgressDialog(); } }) { @Override public Priority getPriority() { return priority; } };