Android's HTTP Class library volley introductory Learning tutorial _android

Source: Internet
Author: User
Tags getmessage http request git clone

1. What is volley
We usually need network technology when we develop Android apps, and in most cases the HTTP protocol is used by applications to send and receive network data. The Android system provides two main ways to do HTTP communications, HttpURLConnection and HttpClient, which we can see in almost any project's code, with very high usage rates.

However, the use of httpurlconnection and httpclient is slightly more complex, and if not properly encapsulated, it is easy to write a lot of duplicate code. As a then, some of the Android network communication framework came into being, such as asynchttpclient, which encapsulates all of the HTTP communication details inside, and we can simply call a few lines of code to complete the communication operation. Another example is Universal-image-loader, which makes it extremely easy to display Web images on the interface, and developers don't care about how to get pictures from the web, and don't care about opening threads, recycling picture resources, and more. Universal-image-loader has done everything well.

The Android development team is also aware of the need to simplify HTTP communication operations, so at the 2013 Google I/O Conference launched a new framework for network communications--volley. Volley said it is the asynchttpclient and Universal-image-loader advantages set in one, can be as asynchttpclient as very simple HTTP communication, You can also load pictures on the network as easily as Universal-image-loader. In addition to ease of use, volley in the performance of a significant adjustment, it is designed to be very suitable for the amount of data, but the network operation of frequent communication, and for large data network operations, such as downloading files, volley performance will be very bad.
1.1. Volley introduced in the background
in the past, we may face a lot of problems as follows.

For example, the previous steps for downloading pictures from the web may be such a process:

    • Start the reading of the image in Listadapter#getview ().
    • Use HttpURLConnection to go from server to picture resources through asynctask and other mechanisms
    • Set the properties of the corresponding ImageView in Asynctask#onpostexecute ().
    • In the volley, you need only one function, see the example in detail later.

For example, when the screen rotates, it sometimes causes the data to be obtained again from the network. To avoid this unnecessary internet access, we may need to write a lot of things for ourselves, such as cache or something.

Again, such as ListView, we scroll too fast, may cause some network requests to return, has already rolled over the position of the time, there is no need to show in the list, although we can through viewholder to maintain the URL, etc. to achieve to prevent two of times to obtain, But there is no need for the data, or waste the resources of the system.

Features provided by 1.2. Volley
in simple terms, it provides the following convenience features:

    • The asynchronous downloading of JSON, images, etc.;
    • Ordering of network requests (scheduling)
    • Priority processing for network requests
    • Cache
    • Multi-level cancellation request
    • Activity and Lifecycle linkage (all network requests are canceled at the end of the activity)

2. Pre-use preparation

Introduction of volley is very simple, first of all, from the GIT library first cloned down:

git clone Https://android.googlesource.com/platform/frameworks/volley 

Then compile the jar package and import it into your project.

Note that this library requires a minimum SDK version of Froyo, that is, to set android:minsdkversion to at least 8.

3. Examples of Use
Here's a quick look at how to use volley

3.1. The simplest GET request
This example is very simple, get the JSON object from the network and print it out.

Mqueue = Volley.newrequestqueue (Getapplicationcontext ()); 
Mqueue.add (New Jsonobjectrequest (method.get, URL, null, 
   new Listener () { 
    @Override public 
    void Onresponse (Jsonobject response) { 
     log.d (TAG, "response:" + response.tostring ()); 
    } 
   }, null); 
Mqueue.start (); 

3.2. Set picture Source for ImageView

ImageView is a ImageView instance 
//Imageloader.getimagelistener The second parameter is the default picture resource ID 
//The third parameter is the resource ID when the request fails. can be specified as 0 
imagelistener listener = Imageloader.getimagelistener (ImageView, Android. R.drawable.ic_menu_rotate, Android. R.drawable.ic_delete); 
Mimageloader.get (URL, listener); 

Imageloader methods need to be invoked from the main thread.

3.3. Use of Networkimageview

Volley provides a new control Networkimageview to replace the traditional ImageView, the control's picture properties can be

Mimageview.setimageurl (URL, imageloader) 

To set. Also, the control automatically cancels the network request when it is detach from the parent control, which is completely free of our concern about the lifecycle of the related network request.
The sample code is as follows:

Mimageloader = new Imageloader (Mrequestqueue, New Bitmaplrucache ()); 
... ... 
 
if (holder.imagerequest!= null) { 
 holder.imageRequest.cancel (); 
} 

Note that this is not a imageview control, but rather a volley newly supplied Com.android.volley.NetworkImageView.

In addition, note here:

Mimageloader = new Imageloader (Mrequestqueue, New Bitmaplrucache ()); 

The second parameter of the Imageloader constructor is a Imagecache instance (strictly, an instance of a specific class that implements the Imagecache interface)
Imagecache is defined as follows (in Imageloader.java):

/** 
 * Simple Cache adapter interface. If provided to the imageloader, it * would be used as a L1 cache before to dispatch 
 . Implementations 
 * must not block. Implementation with a LruCache is recommended. 
 * * Public 
interface Imagecache {public 
 Bitmap getbitmap (String URL); 
 public void Putbitmap (String url, Bitmap Bitmap); 
} 

Below the URL of a LRU cache implementation example, please refer to:
Https://github.com/suwa-yuki/VolleySample/blob/master/src/jp/classmethod/android/sample/volley/BitmapCache.java

The use of 3.4 stringrequest
initiates an HTTP request, and then receives an HTTP response. First you need to obtain a Requestqueue object, which you can call the following methods to obtain:

Requestqueue Mqueue = volley.newrequestqueue (context); 

Note that the requestqueue here is a request queue object that caches all HTTP requests, and then sends those requests concurrently with a certain algorithm. The internal design of requestqueue is very suitable for high concurrency, so we don't have to create a Requestqueue object for every HTTP request, which is a waste of resources, Basically creating a Requestqueue object in each activity that needs to interact with the network is sufficient.

Next, in order to send an HTTP request, we also need to create a Stringrequest object, as follows:

Stringrequest stringrequest = new Stringrequest ("Http://www.baidu.com", 
      new Response.listener<string> () { 
       @Override public 
       void Onresponse (String response) { 
        log.d ("TAG", response); 
       } 
      , new Response.errorlistener () { 
       @Override public 
       void Onerrorresponse (volleyerror error) { 
        log.e ("TAG"). Error.getmessage (), error); 
       } 
      ); 

As you can see, here's a new Stringrequest object, the Stringrequest constructor needs to pass in three parameters, the first parameter is the URL address of the target server, the second parameter is the server's response to a successful callback, and the third parameter is the server's response to the failed callback. In which, the target server address we fill out the homepage of Baidu, and then in response to a successful callback to print out the contents of the server returned, in response to the failure of the callback to print out the failure of the detailed information.

Finally, you can add this Stringrequest object to the Requestqueue, as follows:

Mqueue.add (stringrequest);
In addition, since volley is to access the network, do not forget to add the following permissions to your Androidmanifest.xml:

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

Well, that's simple, if you run the program now and send an HTTP request, you'll see that the data shown in the Logcat will be printed in the image below.

Yes, Baidu returned to us is such a long string of HTML code, although we will look a bit laborious, but the browser can easily parse the HTML code, and then Baidu's home page to show out.

In this way, a basic HTTP send and respond function is completed. You will find that you have not written a few lines of code can easily achieve this function, mainly in the following three steps:

(1). Create a Requestqueue object.

(2). Create a Stringrequest object.

(3). Add the Stringrequest object to the Requestqueue.

But as you know, there are usually two types of requests for HTTP, get and post, and what we're obviously using is a got request, so what do you do if you want to send a POST request? Another four-parameter constructor is provided in the Stringrequest, where the first parameter specifies the request type, which we can specify by using the following method:

Stringrequest stringrequest = new Stringrequest (method.post, URL, Listener, errorlistener);
But this only specifies the HTTP request method is post, then we want to submit the parameters of the server how to set it? Unfortunately, Stringrequest does not provide a way to set the post parameter, but when a POST request is made, volley attempts to invoke the Getparams () method in the Stringrequest parent class--request to get the post parameter , the solution is naturally, and we just need to rewrite the Getparams () method in the anonymous class of Stringrequest, where we can set the post parameters, and the code looks like this:

Stringrequest stringrequest = new Stringrequest (method.post, URL, Listener, Errorlistener) { 
 @Override 
 Protected Map<string, string> Getparams () throws Authfailureerror {map<string 
  , string> Map = new 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 are no methods to set post parameters. But do not forget, volley is open source, as long as you are willing, you are free to add and modify any method inside, easily can customize a volley version that belongs to you.

The use of 3.5 jsonrequest
After learning the most basic stringrequest usage, let's take a step further and learn the jsonrequest usage. Similar to Stringrequest,jsonrequest is inherited from the request class, but since Jsonrequest is an abstract class, so we cannot directly create an instance of it, then we can only start with its subclasses. Jsonrequest have two direct subclasses, Jsonobjectrequest and jsonarrayrequest, you should be able to tell the difference from the name? One is for requesting a section of JSON data, and one for requesting a JSON array.

As for their usage, there is basically nothing special about it, first to new a Jsonobjectrequest object, as shown here:

Jsonobjectrequest jsonobjectrequest = new Jsonobjectrequest ("http://m.weather.com.cn/data/101010100.html", 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) { 
    log.e ("TAG", Error.getmessage (), error); 
   } 
  ); 

Can see, here we fill in the URL address is http://m.weather.com.cn/data/101010100.html, this is the Chinese weather Network to provide a query weather information interface, the response data is returned in JSON format, We then print the returned data in the Onresponse () method.

Finally, add the Jsonobjectrequest object to the Requestqueue, as follows:

Mqueue.add (jsonobjectrequest); 

This way, when HTTP traffic is complete, the weather information that the server responds to will be recalled to the Onresponse () method and printed out. Now run the program and issue an HTTP request, and you will see that the data shown in the Logcat will be printed in the following image.


3.6. Use your own customized request

We can also customize our request by inheriting the request according to our own needs.

@Override 
protected Response parsenetworkresponse (Networkresponse Response) { 
 try { 
  String json = new String ( 
    response.data, Httpheaderparser.parsecharset (response.headers)); 
  Return response.success ( 
    Gson.fromjson (JSON, Clazz), Httpheaderparser.parsecacheheaders (Response)); 
 catch (Unsupportedencodingexception e) {return 
  response.error (new ParseError (e)); 
 Jsonsyntaxexception e) {return 
  response.error (new ParseError (e)); 
 } 
 

This code excerpt from: https://gist.github.com/ficusk/5474673

The Gson (Com.google.gson.Gson) used inside is a library of JSON serialization and deserialization, which can be transformed between JSON and Java model object.

The following are examples of using custom request:

Mrequestqueue.add (new Gsonrequest (URL, listresponse.class, NULL, 
 new Listener () {public 
  void Onresponse ( Listresponse response) { 
   appenditemstolist (response.item); 
   Notifydatasetchanged ();}} 
 

4. Architecture design of Volley

Volley uses line pool as the infrastructure, mainly divided into main thread, cache thread and network threads.
There is only one main thread and cache thread, and Networkdispatcher threads can have multiple, which can solve the problem of parallelism. The following figure:

If a network request is launched within an activity, and if the activity is ended when the network request has not returned a result, we need to write the following code as defense:

@Override public void OnPostExecute (Result r) { 
 if (getactivity () = null) {return 
  ; 
 } 
 // ... 
} 

After the activity is terminated, if you continue to use the context and so on, in addition to the innocent waste of CPU, batteries, networks and other resources, may also lead to program crash, so we need to deal with this situation.

With volley, we can cancel all or some of the incomplete network requests while the activity stops.

All the request results in the volley are returned to the main process, and if certain requests are canceled in the main process, the requests are not returned to the main thread.
For example, you can cancel an operation on some request:

@Override public 
void OnStop () {for 
 (Request <?> req:minflightrequests) { 
  req.cancel () 
 } 
 . . 
} 

Or, cancel all requests in this queue:

@Override pubic void OnStop () { 
 mrequestqueue.cancelall (this); 
 ... 
} 

You can also terminate certain requests based on Requestfilter or tag:

@Override public void OnStop () { 
 mrequestqueue.cancelall (new Requestfilter () {}) 
 ... 
 or 
 Mrequestqueue.cancelall (new Object ()); 
 ... 

5. Summary

From the example of the lecture, volley should simplify some of the development of network communication, especially for the following two situations:

    • JSON object
    • Picture loading

But this thing also has some impractical places, such as large data (large payloads), streaming media, these case, also need to use the original method, such as Download Manager.

Anyway, if you want to write a Web program, can you consider starting to use volley?

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