Network Request Library Volley

Source: Internet
Author: User
Tags null null

    1. Introduced
    2. Volley
    3. Create Requestqueue
    4. Using Requestqueue
      • Stringrequest
      • Jsonrequest
      • Imagerequest
    5. POST request
    6. Cancel Request
    7. Priority of the request
      • List of priority levels

1. Introduction

Typically volley uses only two classes of requestqueue and request, first creating a requestqueue,requestqueue management worker thread and sending the parsed results to the main thread. Then pass one or more request objects to him.

The parameters of the request's constructor contain the requested type (GET, POST, and so on), the URL of the data source, and the event listener. Depending on the type of request, some additional parameters may be required.

2, Volley3, create Requestqueue
 Public classMarsweatherextendsApplication {PrivateRequestqueue Mrequestqueue; Private StaticMarsweather minstance; @Override Public voidonCreate () {Super. OnCreate (); Minstance= This; Mrequestqueue=Volley.newrequestqueue (Getapplicationcontext ()); }       Public Static synchronizedMarsweather getinstance () {returnminstance; }     Public Static FinalString TAG = Marsweather.class. GetName ();  Publicrequestqueue Getrequestqueue () {returnMrequestqueue; }       Public<T>voidAdd (request<t>req) {Req.settag (TAG);//tag can be any valueGetrequestqueue (). Add (req); }       Public voidCancel () {Mrequestqueue.cancelall (TAG); }      }

Note : If you created it in application, add the attribute android:name= under the application tag in the androidmanifest.xml file . Marsweather" can only be used

4. Using Requestqueue

Volley implements three common types of requests:

    • Stringrequest
    • Jsonrequest
    • Imagerequest
4.1 stringrequest
String url = "http://httpbin.org/html"; //Request A string responseStringrequest stringrequest =Newstringrequest (Request.Method.GET, URL,NewResponse.listener<string>() {@Override Public voidOnresponse (String response) {//Request Response succeededSystem.out.println (Response.substring (0,100)); }}, NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {//request failedSystem.out.println ("Something went wrong!");    Error.printstacktrace ();  }}); //ADD the request to the queueVolley.newrequestqueue ( This). Add (Stringrequest);
4.2 jsonrequest
String url = "Http://httpbin.org/get?site=code&network=tutsplus"; Jsonobjectrequest jsonrequest=Newjsonobjectrequest (Request.Method.GET, URL,NULL,NewResponse.listener<jsonobject>() {@Override Public voidOnresponse (jsonobject response) {//The response is already constructed as a jsonobject!                Try{Response= Response.getjsonobject ("args"); String site= response.getstring ("Site"), Network= response.getstring ("Network"); System.out.println ("Site:" +site+ "\nnetwork:" +network); } Catch(jsonexception e) {e.printstacktrace (); }            }        }, NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {error.printstacktrace ();  }        }); Volley.newrequestqueue ( This). Add (Jsonrequest);

If you need to, you can also request Jsonarray, just use jsonarrayrequest instead of jsonobjectrequest.

4.3 imagerequest

Because there is a request for a picture, there is no http type parameter, and the picture request is always get. There are three ways to request pictures.

4.3.1.,imagerequest. By providing the URL, she displays the picture you requested in a regular imageview. Both the compression and sizing operations occur in the worker thread.

String url = "Http://i.imgur.com/Nwk25LA.jpg"; Mimageview=(ImageView) Findviewbyid (r.id.image); Imagerequest imgrequest=Newimagerequest (URL,NewResponse.listener<bitmap>() {@Override Public voidOnresponse (Bitmap response) {Mimageview.setimagebitmap (response); }}, 0, 0, ImageView.ScaleType.FIT_XY, Bitmap.Config.ARGB_8888,NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {Mimageview.setbackgroundcolor (Color.parsecolor ("#ff0000"));    Error.printstacktrace (); }});
Volley.newrequestqueue ( This). Add (Imgrequest);

The first parameter is the URL of the picture, the second is the listener of the result, the third and fourth parameters are maxwidth (maximum width) and maxheight (maximum height), which can be set to zero to ignore them. Then is the scaletype for calculating the desired size of the picture, then the parameters used to specify how the picture is compressed, I recommend always using Bitmap.Config.ARGB_8888, and finally an error listener.

Note: Volley the priority of this request is set to low by default.

@Override  Public Priority GetPriority () {    return  priority.low;}

4.3.2 , Imageloader class. You can think of it as a large number of imagerequests, such as creating a ListView with a picture.

//Imageloader This class requires an instance of request and an instance of Imagecache, but volley does not provide a default implementationRequestqueue Mrequestqueue= Volley.newrequestqueue ( This);Finallrucache<string, bitmap> Mimagecache =NewLrucache<string, bitmap>(20); Imagecache Imagecache=NewImagecache () {@Override Public voidPutbitmap (String key, Bitmap value) {mimagecache.put (key, value); } @Override PublicBitmap Getbitmap (String key) {returnMimagecache.get (key); }};
Imageloader Mimageloader=NewImageloader (Mrequestqueue, imagecache);//ImageView is a ImageView instance//the second parameter of Imageloader.getimagelistener is the default picture resource ID//The third parameter is the resource ID at the time of the request failure and can be specified as 0Imagelistener listener =Imageloader.getimagelistener (ImageView, Android. R.drawable.ic_menu_rotate,android. R.drawable.ic_delete); Mimageloader.get (URL, listener); //This method will load the image

4.3.3, Networkimageview.

//inherit from ImageView Public classNetworkimageviewextendsImageView//added a Setimageurl method that contains a URL address and a Imageloader object, Imageloader can refer to the above Public voidsetimageurl (String URL, Imageloader imageloader) {}//Core ApproachPrivate voidLoadimageifnecessary (Final BooleanIsinlayoutpass) {    //internal implementation, a Boolean parameter that represents whether the network is re-requested, true: Re-request false: Fetch cache//The internal implementation and Imageloader are similar, all through Imagecontainer in the new one Imagelistener, in the Imagelistener, just do the null judgment of the URL, if the URL is null, Call Imagecontainer.cancelrequest (); cancel the request. }  

Network request download picture display, you can use this control, more than the traditional ImageView network processing, also added 2 methods, set the start download the default diagram and download error after the display diagram.

 Public void setdefaultimageresid (int  defaultimage) {  = defaultimage;  }    Public void seterrorimageresid (int  errorimage) {  = errorimage;  

5. Post Request

Switching from a GET request to a POST request is straightforward. You only need to change the Request.method in the constructor method of the request, while overriding the Getparams method, returning the map<string containing the request parameters, string>.

String url = "Http://httpbin.org/post"; Stringrequest postrequest=Newstringrequest (Request.Method.POST, URL,NewResponse.listener<string>() {@Override Public voidOnresponse (String response) {Try{jsonobject Jsonresponse=NewJsonobject (response). Getjsonobject ("form"); String site= jsonresponse.getstring ("Site"), Network= jsonresponse.getstring ("Network"); System.out.println ("Site:" +site+ "\nnetwork:" +network); } Catch(jsonexception e) {e.printstacktrace (); }            }        },        NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {error.printstacktrace (); }        }
) {@OverrideprotectedMap<string, string>Getparams () {Map<string, string> params =NewHashmap<>(); //This returns the post parameter:Params.put ("Site", "code"); Params.put ("Network", "Tutsplus"); returnparams; }}; Volley.newrequestqueue ( This). Add (Postrequest);
6. Cancellation Request

If you want to cancel all requests, add the following code to the OnStop method:

 @Override   void   OnStop () { super  .onstop (); Mrequestqueue.cancelall ( new   Requestqueue.requestfilter () {@Override  public  boolean  Apply (Request<?> Request) { //  do I had to cancel the this?  return  true ; //   

You can also cancel requests based on tags. For example, when constructing a GET request, set a tag:

Request.settag ("GET"); Mrequestqueue.add (request);

Cancel a request with tag "GET"

Suppose you already have a Requestqueue variable

7. Priority of Request

By default, volley sets the priority of the request to normal. Generally this is not a problem, however, in our application, the difference between the two requests is very large, it is necessary to let them have different priorities in the queue. You need to rewrite a request

 Public classCustomjsonrequestextendsJsonobjectrequest { PublicCustomjsonrequest (intmethod, String URL, jsonobject jsonrequest, Response.listener<JSONObject>Listener, Response.errorlistener Errorlistener) {        Super(method, URL, jsonrequest, Listener, Errorlistener); }      PrivatePriority Mpriority;  Public voidSetPriority (Priority priority) {Mpriority=Priority ; } @Override PublicPriority GetPriority () {returnMpriority = =NULL?Priority.NORMAL:mPriority; }}
Newnullnull null); // for the simple code, it is convenient to demonstrate the SetPriority method, I set the above listener all to null

Request.setpriority (Request.Priority.HIGH); Volley.newrequestqueue (Getapplicationcontext ());. Add (Request);
List of priority levels
// images, thumbnails, ... // residual // descriptions, lists, ... // login, logout, ...

Network Request Library Volley

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.