Reprinted please indicate the source: http://blog.csdn.net/guolin_blog/article/details/17482095
1. Volley Introduction
We usually use network technology when developing Android applications. In most cases, applications use the HTTP protocol to send and receive network data. The Android system mainly provides two methods for HTTP Communication: HttpURLConnection and HttpClient. We can see these two classes in almost any project code, and the usage is very high.
However, the use of HttpURLConnection and HttpClient is a little complicated. If it is not properly encapsulated, it is easy to write a lot of repeated code. As a result, some Android Network Communication frameworks have emerged. For example, AsyncHttpClient encapsulates all the communication details of HTTP, we only need to call a few lines of code to complete the communication operation. For another example, Universal-Image-Loader makes it extremely simple to display network images on the interface. Developers do not have to worry about how to obtain images from the network, you don't have to worry about opening threads, recycling Image resources, and other details. Universal-Image-Loader has done everything well.
The Android development team realized that it was necessary to simplify HTTP Communication Operations. So at the Google I/O conference in 2013, a new network communication framework, Volley, was launched. Volley combines the advantages of AsyncHttpClient and Universal-Image-Loader to implement HTTP Communication as easily as AsyncHttpClient, you can also easily attach images on the network like Universal-Image-Loader. In addition to ease of use, Volley has also made significant adjustments in terms of performance. Its design goal is to be very suitable for performing a small amount of data, but frequent network operations, for network operations that involve a large amount of data, such as file downloads, Volley performs very poorly.
As shown in the preceding figure, Volley is suitable for applications with small data volumes but frequent network communication.
2. Download Volley
After introducing so many theoretical things, let's prepare for the actual practice. First, we need to prepare the Volley jar package. If your computer is installed with Git, you can use the following command to download the Volley source code:
git clone https://android.googlesource.com/platform/frameworks/volley
After the download is complete, import it to your Eclipse project, and then export a jar package. If you don't have Git on your computer, you can also directly use the jar package I exported, which is: http://download.csdn.net/detail/sinyu890807/7152015.
Create an Android project and copy the volley. jar file to the libs directory. This completes the preparation.
3. Usage of StringRequest
As mentioned above, Volley is easy to use. Let's start with the basic HTTP communication, that is, to initiate an HTTP request and then receive the HTTP response. First, you must obtain a RequestQueue object. You can call the following method to obtain it:
RequestQueue mQueue = Volley.newRequestQueue(context);
Note that the RequestQueue obtained here is a request queue object, which can cache all HTTP requests and then send these requests concurrently according to certain algorithms. The internal design of RequestQueue 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, it is enough to create a RequestQueue object in every Activity that needs to interact with the network.
Next, to send an HTTP request, we also need to create a StringRequest object, as shown below:
StringRequest stringRequest = new StringRequest("http://www.baidu.com",new Response.Listener<String>() {@Overridepublic void onResponse(String response) {Log.d("TAG", response);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.e("TAG", error.getMessage(), error);}});
We can see that a new StringRequest object is generated. The StringRequest constructor needs to input three parameters. The first parameter is the URL address of the target server, the second parameter is the callback for successful server response, and the third parameter is the callback for failed server response. Here, we enter the address of the target server on the Baidu homepage, and then print the content returned by the server in the response success callback, and print the failure details in the response failure callback.
Finally, add the StringRequest object to RequestQueue, as shown below:
mQueue.add(stringRequest);
In addition, because Volley wants to access the network, do not 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 and send such an HTTP request, you will see the data shown in LogCat.
That's right. What Baidu returns to us is such a long string of HTML code. Although it seems a little difficult, the browser can easily parse this HTML code, then display the Baidu homepage.
In this way, a basic HTTP sending and response function is complete. You will find that this function is easily implemented without writing a few lines of code, mainly through the following three steps:
1. Create a RequestQueue object.
2. Create a StringRequest object.
3. Add the StringRequest object to RequestQueue.
However, we all know that there are two types of HTTP requests: GET and POST. We used a GET request. What should we do if we want to send a POST request? StringRequest also provides another constructor with four parameters. The first parameter specifies the request type, which can be specified as follows:
StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener);
However, this only specifies that the HTTP request method is POST. How can we set the parameters to be submitted to the server? Unfortunately, the StringRequest does not provide a method to set the POST parameter. However, when a POST Request is sent, Volley tries to call the StringRequest parent class -- getParams () in the Request () method to obtain the POST parameter, then the solution will naturally be available. We only need to re-write the getParams () method in the anonymous class of StringRequest. Here we can set the POST parameter, the Code is as follows:
StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener) {@Overrideprotected 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, isn't it tiring to use it like this every time? There are no methods for setting the POST parameter. But don't forget that Volley is open-source. As long as you want, you can freely add and modify any methods in it to easily create a Volley version of your own.
4. JsonRequest usage
After learning the basic usage of StringRequest, let's take a look at the usage of JsonRequest. Similar to StringRequest, JsonRequest also inherits from the Request class. However, because JsonRequest is an abstract class, we cannot directly create its instance, so we can only start with its subclass. JsonRequest has two direct sub-classes: JsonObjectRequest and JsonArrayRequest. You should be able to see their differences from their names, right? One is used to request a piece of JSON data, and the other is used to request a piece of JSON array.
There is basically nothing special about their usage. First, a JsonObjectRequest object is created, as shown below:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://m.weather.com.cn/data/101010100.html", null,new Response.Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {Log.d("TAG", response.toString());}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.e("TAG", error.getMessage(), error);}});
We can see that the URL we entered here is the response () method to print the returned data.
Add the JsonObjectRequest object to RequestQueue, as shown below:
mQueue.add(jsonObjectRequest);
In this way, after the HTTP Communication is complete, the weather information returned by the server will be called back to the onResponse () method and printed out. Run the program and send such an HTTP request. The data shown in figure is printed in LogCat.
From this we can see that the data returned by the server to us is indeed in JSON format, and the parameters in the onResponse () method are exactly a JSONObject object, then, you only need to retrieve the part of the data we want from the JSONObject object.
You should have discovered that the usage of JsonObjectRequest is basically the same as that of StringRequest, and Volley's ease of use is also reflected here, I believe that the JsonArrayRequest usage does not need to be explained.
Now, let's talk about the basic usage of Volley. In the next article, I will continue to explore Volley.