Android Volley fully Parse (a), the basic usage of first knowledge volley

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/17482095

1. Volley Introduction

We usually need to use network technology when developing Android applications, and in most cases the application uses the HTTP protocol to send and receive network data. There are two main ways to make HTTP communication in the Android system, HttpURLConnection and httpclient, we can see these two categories in almost any project code, the usage rate is very high.

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. So, some of the Android network communication framework has come into being, for example, asynchttpclient, it has all the communication details of HTTP encapsulated inside, we 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 have to worry about how to get pictures from the web, or how to turn on threads, recycle picture resources, etc. Universal-image-loader has done everything well.

The Android development team was also aware of the need to simplify the communication of HTTP, so a new network communication framework--volley was introduced at the 2013 Google I/O conference. Volley but the asynchttpclient and universal-image-loader of the advantages of the set in one, can be as very simple as asynchttpclient http communication, You can also load pictures on your network as easily as Universal-image-loader. In addition to simple and easy to use, volley in the performance of the large-scale adjustment, its design goal is very suitable for the volume of data is not small, but the traffic is frequent network operation, and for large data volume of network operations, such as downloading files, volley performance will be very bad.

The applications shown are all of a small amount of data, but network traffic is frequent, making it ideal for use with volley.

2. Download Volley

Introduced so many theories of things, we are ready to start the actual combat, the first need to volley jar package ready, if your computer installed Git, you can use the following command to download volley Source:

1 git clone https://Android.googlesource.com/platform/frameworks/volley

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 I exported, which is: http://download.csdn.net/detail/sinyu890807/7152015.

Create a new Android project and copy the Volley.jar file to the Libs directory, so the preparation is done.

3. Usage of Stringrequest

As we have already said, the usage of volley is very simple, so let's start with the most basic HTTP communication, which is to initiate an HTTP request and then receive the HTTP response. First, you need to get to a Requestqueue object, which can be obtained by invoking the following methods:

Note that the requestqueue here is a request queue object that caches all 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, which is a waste of resources, Basically creating a Requestqueue object in every activity that needs to interact with the network is sufficient.

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

1Stringrequest stringrequest =NewStringrequest ("http://www.baidu.com",2                         NewResponse.listener<string>() {3 @Override4                              Public voidOnresponse (String response) {5LOG.D ("TAG", response);6                             }7},NewResponse.errorlistener () {8 @Override9                              Public voidonerrorresponse (volleyerror error) {TenLOG.E ("TAG", Error.getmessage (), error); One                             } A});

As you can see, here New has a Stringrequest object, the constructor of the stringrequest needs to pass in three parameters, the first parameter is the URL address of the target server, the second parameter is the server response successful callback, the third parameter is the server response failed callback. Where the destination server address we fill in the first page of Baidu, and then in response to a successful callback to print out the contents of the server, in response to the failure of the callback to print the failure of the details.

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

1 mqueue.add (stringrequest);  

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

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

Well, it's that simple, if you run the program now and issue an HTTP request, you'll see that the data shown in Logcat is printed.

Yes, Baidu returned to us is such a long list of HTML code, although we seem to be a little hard, but the browser can easily parse this piece of HTML code, and then the Baidu home page to show.

In this case, a basic HTTP send and respond function is complete. You will find that it is easy to implement this function without writing a few lines of code, mainly by doing the following three steps:

1. Create a Requestqueue object.

2. Create a Stringrequest object.

3. Add the Stringrequest object to the Requestqueue.

However, as we all know, the request type of HTTP usually has two, get and post, we used the obvious is a GET request, then if you want to issue a POST request what should be done? Another four-parameter constructor is provided in Stringrequest, where the first parameter is the specified request type, which we can specify using the following method:

New Stringrequest (method.post, URL,  Listener, Errorlistener);  

But this only specifies the HTTP request mode is post, then we have to submit to the server parameters how to set it? Unfortunately, Stringrequest does not provide a way to set the post parameters, but when a POST request is made, volley attempts to invoke the Getparams () method in Stringrequest's parent class--request to get the post parameter , the solution is naturally there, we just need to rewrite the Getparams () method in the anonymous class of Stringrequest, where the post parameters are set, and the code looks like this:

1Stringrequest stringrequest =Newstringrequest (method.post, URL, Listener, Errorlistener) {2 @Override3     protectedMap<string, string> getparams ()throwsAuthfailureerror {4map<string, string> map =NewHashmap<string, string>();5Map.put ("Params1", "value1");6Map.put ("Params2", "value2");7         returnmap;8     }9};

You might say that it's tiring to use it all the time? There is no way to set a post parameter. But do not forget that volley is open source, as long as you are willing, you are free to add and modify any of the methods, you can easily customize a volley version of your own.

4. Usage of jsonrequest

After learning the basic usage of stringrequest, let's go to the advanced level and learn about the use of jsonrequest. 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, we can only start with its subclasses. Jsonrequest There are two direct subclasses, Jsonobjectrequest and Jsonarrayrequest, can you tell the difference from the name? One is used to request a piece of JSON data, and one is used to request a JSON array.

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

1Stringrequest stringrequest =Newstringrequest (method.post, URL, Listener, Errorlistener) {2 @Override3     protectedMap<string, string> getparams ()throwsAuthfailureerror {4map<string, string> map =NewHashmap<string, string>();5Map.put ("Params1", "value1");6Map.put ("Params2", "value2");7         returnmap;8     }9};

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

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

1 mqueue.add (jsonobjectrequest);  

When the HTTP communication is complete, the server responds with the weather information back to the Onresponse () method and prints it out. Now run the program, make an HTTP request, and you will see that the data shown in Logcat will be printed.

As you can see, the data returned to us by the server is indeed in JSON format, and the parameters that are carried in the Onresponse () method are exactly the same as a Jsonobject object, and then only the part of the data that we want to get out of the Jsonobject object is available.

You should find out, jsonobjectrequest usage and stringrequest usage is basically the same, volley's ease of use is also reflected here, will be a kind of can let you extrapolate, So I believe I don't need to explain the usage of jsonarrayrequest.

Android Volley fully Parse (a), the basic usage of first knowledge 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.