Android--volley FRAME (i)

Source: Internet
Author: User
Tags http authentication

1. Volley Introduction (2013 I/O Conference)

There are two main ways to do HTTP communication in Android, HttpURLConnection and HttpClient

    1. Asynchttpclient, it encapsulates all the communication details of HTTP in the interior, we simply call a few lines of code to complete the communication operation.
    2. Universal-image-loader, which makes it extremely easy to display Web images on the interface, developers don't have to worry about how to get pictures from the web, or how to open threads, recycle pictures, etc. , Universal-image-loader has done everything well.

Java's entity class to encapsulate the data.

Https:// enhanced version of volley added the ability to upload files

Request Header settings:: Overriding the Getheaders method
Timeout setting: Overriding the Getretrypolicy method
Request parameter assembly: overriding the GetBody method
    1. Authfailureerror: This error may occur if you are doing an HTTP authentication.
    2. Networkerror:socket shutdown, server down, DNS errors will generate this error.
    3. Noconnectionerror: Similar to Networkerror, this is a client with no network connection.
    4. ParseError: When using Jsonobjectrequest or jsonarrayrequest, if the JSON received is malformed, an exception is generated.
    5. Servererror: An error in the response of the server, most likely the 4xx or 5xx HTTP status code.
    6. The Timeouterror:socket times out, the server is too busy, or the network latency causes this exception. By default, the volley time-out is 2.5 seconds. If you get this error, you can use Retrypolicy.

2. Download Volley

First, you need to prepare the volley jar package, if you have Git installed on your computer, you can use the following command to download the volley source code:

git clone Https:// //This is the source code of volley, can export volley jar package

After the download is complete, import it into your Eclipse project and then export a jar package.

If you don't have git on your computer, you can also use the jar package that I exported, which is: .

Copy the Volley.jar file to the Libs directory , so the preparation is done.

3. Usage of stringrequest (service-side return string)

1. Create a Requestqueue object.

2. Create a Stringrequest object. The GET request is a 3 constructor method, and the post request is a method of 4 constructor + parent class (for passing parameters).

3. Add the Stringrequest object to the Requestqueue.

Requestqueue one activity to create one is enough.

requestqueue mqueue = volley.newrequestqueue (context);  

Requestqueue (high concurrency) is a request queue object that caches all HTTP requests (40 500 interface HTTP requests) and then makes these requests in parallel with a certain algorithm. Requestqueue internal design is very suitable for high concurrency , so we do not have to create a Requestqueue object for every HTTP request, this is a very wasteful resource, basically It is sufficient to create a Requestqueue object in each activity that needs to interact with the network .

String url = "Http://";

stringrequestStringrequest =NewStringrequest (//stringrequest is a request object
Parameter 1, request type GET or post
Listener for Successful requestNewResponse.listener<string>() {@Override Public voidOnresponse (String response) {LOG.D ("TAG", response); This parameter is the content that requests the successful server to return, directly prints the}},
Listener for failed requests
NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {LOG.E ("TAG", Error.getmessage (), error); Print failed details});

Finally, add this Stringrequest object to the Requestqueue, as shown below:

Mqueue.add (stringrequest);  

Also, since volley is going to access the network, don't forget to add the following permissions in your Androidmanifest.xml:

<android:name= "Android.permission.INTERNET"/>  

another constructor for four parameters (for a POST request) is provided in stringrequest, but unfortunately Stringrequest does not provide a method for post parameters.

New Stringrequest (, URL,  Listener, errorlistener);   //This only specifies the type of the request is the post type, but no parameters are passed

Unfortunately,Stringrequest does not provide a way to set the post parameters , but when a POST request is made, volley tries to invoke the parent class of Stringrequest-- The Getparams () method in the request class to get the post parameters , the workaround is natural, and we only need to rewrite the getparams() method in the anonymous class of Stringrequest. The post parameters are set here , and the code looks like this:

New stringrequest (, URL,  Listener, Errorlistener) {  
Four parameters + A parent class method (set the parameters for the POST request here) uses the anonymous class @Override protectedgetparams Throws Authfailureerror { //getparams method Mapnew hashmap<string, string> (); Map.put ("Params1", "value1"); Map.put ("Params2", "value2"); return map; }

You might say that it's tiring to use it all the time? There is no way to set a post parameter. But don't forget that volley is open source, and you are free to add and modify any method in it if you wish.

4. Jsonrequest (abstract class-Cannot create an instance of it, only starts with its subclasses), inherits from the request

Jsonrequest has two direct sub-classes:

    • Jsonobjectrequest is used to request a piece of JSON data.
    • The jsonarrayrequest is used to request a JSON array.

Summary jsonobjectrequest and Jsonarrayrequest and stringrequest are basically the same.

As for their usage there is basically nothing special about it, first new out a Jsonobjectrequest object, as follows:

Four Parameters
Jsonobjectrequest jsonobjectrequest =NewJsonobjectrequest ("",NULL,//China Weather NET provides an interface for querying weather informationNewResponse.listener<jsonobject>() {@Override Public void onresponse(jsonobject response) {LOG.D ("TAG", response.tostring ()); And then copy the data from here to the control}},
     NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {LOG.E ("TAG", Error.getmessage (), error); } });

And finally add this Jsonobjectrequest object to the Requestqueue.

Mqueue.add (jsonobjectrequest);  

The advanced usage of the public <T> request<t> startrequest (request<t> r, object tag) generic means that the passed object is either its subclass or its parent class.

2. Image loading

2.1 Download picture using Imagerequest Volley provides a variety of request methods, Imagerequest can process a single picture, return bitmap. Here is an example of the use of imagerequest, as in Jsonrequest.
singleimg=(ImageView) Findviewbyid (; Imagerequest imgrequest=NewImagerequest (URL,NewResponse.listener<bitmap>() {@Override Public voidonresponse (Bitmap arg0) {//TODO auto-generated Method StubSingleimg.setimagebitmap (arg0); }          }, config.argb_8888,NewErrorlistener () {@Override Public voidonerrorresponse (Volleyerror arg0) {//TODO auto-generated Method Stub                              }                     });  Mrequestqueue.add (imgrequest); 
2.2 Using Imageloader

Imageloader This class requires an instance of request and an instance of Imagecache. The picture can be loaded through a URL and a Get () method of a Imagelistener instance. From there, Imageloader will check the Imagecache, and if there are no pictures in the cache, it will be taken from the network.

Volley's Imagecache interface allows you to use your favorite L1 cache implementations. Unfortunately, volley does not provide a default implementation. The introduction of I/O shows a bit of code snippet for Bitmaplrucache, but the volley library itself does not contain any related implementations.

The Imagecache interface has two methods, Getbitmap (string url) and Putbitmap (string URL, Bitmap Bitmap). These two methods are straightforward enough to add any cache implementation.

Requestqueue 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); 
2.3 Using Networkimageview
 Public class extends ImageView  

 inherits from ImageView and adds a
 Public void setimageurl (String URL, Imageloader imageloader) {}  

method, the parameter contains a URL address and a Imageloader object
Core approach:

Private void loadimageifnecessary (finalboolean isinlayoutpass) {}  

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.
Overwrite method:

@Overrideprotected voidOnLayout (BooleanChangedintLeftintTopintRightintbottom) {Super. OnLayout (changed, left, top, right, bottom); //re-request when OnLayoutLoadimageifnecessary (true); } @Overrideprotected voidOndetachedfromwindow () {//release operation when destroying view    if(Mimagecontainer! =NULL) {//If The view is bound to an image request, cancel it and clear//The image from the view.       mimagecontainer.cancelrequest (); Setimagebitmap (NULL); //also clear out the container so we can reload the image if necessary. Mimagecontainer =NULL; }Super. Ondetachedfromwindow (); }  //drawable State Change Redraw@Overrideprotected voiddrawablestatechanged () {Super. drawablestatechanged ();  Invalidate (); }  

Summary: 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.

/*** Sets the default image resource ID to being used for this view until the attempt to load it * completes.*/   Public voidSetdefaultimageresid (intdefaultimage) {Mdefaultimageid=Defaultimage; }  /*** Sets the error image resource ID to is used for this view in the event that the image * requested fails to load. 
    */   Public voidSeterrorimageresid (interrorimage) {Merrorimageid=Errorimage; }  

Android--volley FRAME (i)

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: 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.