Volley provides a graceful framework that makes Android apps network access easier and faster. The volley abstraction implements the underlying HTTP client library, letting you focus on the details of the HTTP client, focusing on writing more beautiful, clean restful HTTP requests. In addition, the volley request executes asynchronously without blocking the main thread.
Features provided by volley
In brief, it provides the following main functions:
1, encapsulated the asynchronous restful request API;
2, an elegant and robust request queue;
3, an extensible architecture, it enables developers to implement a custom request and response processing mechanism;
4, can use the external HTTP client library;
5, cache policy;
6, custom network image load view (networkimageview,imageloader, etc.);
Why use asynchronous HTTP requests?
Android requires an HTTP request to execute asynchronously, and an android.os.NetworkOnMainThreadException exception may be thrown if an HTTP request is executed on the main thread. Blocking the main thread has some serious consequences, it hinders UI rendering, the user experience is not fluent, and it can lead to scary ANR (application not responding). To avoid these traps, as a developer, you should always make sure that the HTTP request is on a different thread.
How to use Volley
This blog will detail how to use volley in the application Cheng, which will include several aspects:
1. Install and use the Volley library
2. Using the request queue
3. Asynchronous JSON, string request
4. Cancellation Request
5. Retry failed requests, custom request timed out
6. Set the request header (HTTP headers)
7. Use of cookies
8. Error handling
Installing and using the Volley library
The introduction of volley is very simple, first of all, from the GIT library first cloned one down:
git clone https://Android.googlesource.com/platform/frameworks/volley
Then compile the jar package and put the jar package into the Libs directory of your project.
Creating volley Singleton Class
ImportInfo.androidhive.volleyexamples.volley.utils.LruBitmapCache;Importandroid.app.Application;Importandroid.text.TextUtils;Importcom.android.volley.Request;ImportCom.android.volley.RequestQueue;ImportCom.android.volley.toolbox.ImageLoader;ImportCom.android.volley.toolbox.Volley; Public classAppControllerextendsApplication { Public Static FinalString TAG = AppController.class. Getsimplename (); PrivateRequestqueue Mrequestqueue; PrivateImageloader Mimageloader; Private StaticAppController minstance; @Override Public voidonCreate () {Super. OnCreate (); Minstance= This; } Public Static synchronizedAppController getinstance () {returnminstance; } Publicrequestqueue Getrequestqueue () {if(Mrequestqueue = =NULL) {Mrequestqueue=Volley.newrequestqueue (Getapplicationcontext ()); } returnMrequestqueue; } PublicImageloader Getimageloader () {getrequestqueue (); if(Mimageloader = =NULL) {Mimageloader=NewImageloader ( This. Mrequestqueue,NewLrubitmapcache ()); } return This. Mimageloader; } Public<T>voidAddtorequestqueue (request<t>req, String tag) { //Set the default tag if tag is emptyReq.settag (Textutils.isempty (tag)?Tag:tag); Getrequestqueue (). Add (req); } Public<T>voidAddtorequestqueue (request<t>req) {Req.settag (TAG); Getrequestqueue (). Add (req); } Public voidcancelpendingrequests (Object tag) {if(Mrequestqueue! =NULL) {Mrequestqueue.cancelall (tag); } }}
1. Making JSON Object request
String url = ""; ProgressDialog Pdialog=NewProgressDialog ( This);pD Ialog.setmessage ("Loading ...");pD ialog.show (); Jsonobjectrequest Jsonobjreq=Newjsonobjectrequest (method.get, URL,NULL, NewResponse.listener<jsonobject>() {@Override Public voidOnresponse (jsonobject response) {LOG.D (TAG, response.tostring ()); Pdialog.hide (); } }, NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {VOLLEYLOG.D (TAG,"Error:" +error.getmessage ()); //hide the progress dialogpdialog.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=NewProgressDialog ( This);pD Ialog.setmessage ("Loading ...");pD ialog.show (); Jsonarrayrequest req=Newjsonarrayrequest (URL,NewResponse.listener<jsonarray>() {@Override Public voidOnresponse (Jsonarray response) {LOG.D (TAG, response.tostring ()); Pdialog.hide (); } }, NewResponse.errorlistener () {@Override Public voidonerrorresponse (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=NewProgressDialog ( This);pD Ialog.setmessage ("Loading ...");pD ialog.show (); Stringrequest strreq=Newstringrequest (method.get, URL,NewResponse.listener<string>() {@Override Public voidOnresponse (String response) {LOG.D (TAG, response.tostring ()); Pdialog.hide (); } }, NewResponse.errorlistener () {@Override Public voidonerrorresponse (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=NewProgressDialog ( This);pD Ialog.setmessage ("Loading ...");pD ialog.show (); Jsonobjectrequest Jsonobjreq=Newjsonobjectrequest (method.post, URL,NULL, NewResponse.listener<jsonobject>() {@Override Public voidOnresponse (jsonobject response) {LOG.D (TAG, response.tostring ()); Pdialog.hide (); } }, NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {VOLLEYLOG.D (TAG,"Error:" +error.getmessage ()); Pdialog.hide (); }}) {@OverrideprotectedMap<string, string>Getparams () {Map<string, string> params =NewHashmap<string, string>(); Params.put ("Name", "Androidhive"); Params.put ("Email", "[email protected]"); Params.put ("Password", "password123"); returnparams; } }; //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=NewProgressDialog ( This);pD Ialog.setmessage ("Loading ...");pD ialog.show (); Jsonobjectrequest Jsonobjreq=Newjsonobjectrequest (method.post, URL,NULL, NewResponse.listener<jsonobject>() {@Override Public voidOnresponse (jsonobject response) {LOG.D (TAG, response.tostring ()); Pdialog.hide (); } }, NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {VOLLEYLOG.D (TAG,"Error:" +error.getmessage ()); Pdialog.hide (); } }) { /*** Passing some request headers **/@Override PublicMap<string, string> getheaders ()throwsAuthfailureerror {HashMap<string, string> headers =NewHashmap<string, string>(); Headers.put ("Content-type", "Application/json"); Headers.put ("ApiKey", "xxxxxxxxxxxxxxx"); returnheaders; } }; //Adding request to request queueAppcontroller.getinstance (). Addtorequestqueue (Jsonobjreq, tag_json_obj);