English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Problem description: The HttpClient and HttpUrlConnection request methods in the Android SDK are used to handle complex network operations, but when the application is more complex, we need to write a lot of code to handle many things: image caching, request scheduling, etc.
Solution: Volley was born to solve these problems, and it works with2013Year Google I/At the Google I/O conference, it was proposed: making Android application network operations more convenient and faster; abstracting the details of the underlying Http Client implementation, allowing developers to focus more on generating RESTful requests. In addition, Volley executes all requests asynchronously on different threads, avoiding blocking the main thread.
Volley can be said to be a combination of AsyncHttpClient and Universal-Image-Loader's advantages are integrated into one, which can both perform HTTP communication as simply as AsyncHttpClient, and also like Universal-Image-Loader can easily load images from the network just like Volley. In addition to being simple and easy to use, Volley has also made significant adjustments in terms of performance. Its design goal is to be very suitable for network operations with small amounts of data but frequent communication, while for network operations with large amounts of data, such as downloading files, Volley's performance will be very poor
1What are the characteristics of Volley?
Automatically scheduling network requests
Multiple concurrent network connections
Maintaining consistency between disk and memory responses through the use of standard HTTP caching mechanisms
Supports request priority
Supports a powerful API for canceling requests, which can cancel a single request or multiple requests
Easy to customize
Robustness: easy to update UI and get data correctly
Include debugging and tracking tools
2、Volley's RequestQueue and Request
● RequestQueue is used to execute the request queue
● Request is used to construct a request object
● Request objects mainly have the following types:
a. StringRequest the body of the response is a string
b. JsonArrayRequest send and receive JSON array
c. JsonObjectRequest send and receive JSON object
d. ImageRequest send and receive Image
3、Volley usage steps:
(1)Create an Android project and import the volley jar package
(2)GET request method:
//Create a RequestQueue object RequestQueue requestQueue = Volley.newRequestQueue(this); String url="http://api.m.panda.tv/ajax_get_all_subcate?__version=1.0.1.1300&__plat=android"; //Create a request object StringRequest request=new StringRequest(url, new Response.Listener<String>() { /** * The result of a successful request * @param response This parameter is the result of accessing network data */ @Override public void onResponse(String response) { // } }, new Response.ErrorListener() { /** * This method is used to listen to access errors and display the results * 07-19 04:17:13.414: E/tag(1181) ------------- * com.android.volley.VolleyError: * java.lang.SecurityException: * Permission denied (missing INTERNET permission?);========================== */ @Override public void onErrorResponse(VolleyError error) { Log.e("tag","-------------"+ error+"==========================" } }); //Add the Request object to the RequestQueue. requestQueue.add(request);
(3Post request method:
By specifying the request method as Request.Method.POST, it becomes a POST request, and then the getParams method is called again to set the request parameters. When a POST request is sent, Volley attempts to call the getParams() method of the superclass of StringRequest, Request, to obtain the POST parameters.
//Create a RequestQueue object RequestQueue requestQueue = Volley.newRequestQueue(this); String url = "http://api.m.panda.tv/ajax_get_all_subcate”; StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener() { @Override public void onResponse(String response) { Log.e("tag", "Request successful============"+response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("tag", "Request successful============"+error); } }) { /** * Override the getParams method to set parameters, the method to add parameters by post */ @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> params = new HashMap<String, String>(); params.put("__version", "1.0.1.1300"); params.put("__plat", "android"); return params; } }; requestQueue.add(request);
(3) The way to load images:
The first method to load images
RequestQueue requestQueue = Volley.newRequestQueue(context); String img = datas.getImg(); //The third and fourth parameters are used to specify the maximum width and height of the image allowed. If the width or height of the specified network image is greater than the maximum value here, the image will be compressed. Specifying 0 means that no compression will be performed regardless of the size of the image. //The fifth parameter is used to specify the color attribute of the image ImageRequest request = new ImageRequest(img, new Response.Listener<Bitmap>() { @Override public void onResponse(Bitmap response) { holder.iv.setImageBitmap(response); } }, 0, 0, Bitmap.Config.ARGB_8888, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub } }); requestQueue.add(request);
The second method of loading images
In fact, the functionality of loading images is far more than these, using ImageLoader can implement image caching, and can also filter duplicate links to avoid sending duplicate requests
The usage of ImageLoader can be summarized into the following steps
1. Create a RequestQueue object.
2. Create an ImageLoader object.
3. Obtain an ImageListener object.
4. Call ImageLoader's get() method to load images from the network.
//Inherits ImageCache, using LruCache to implement caching public class BitmapCache implements ImageLoader.ImageCache { private LruCache<String, Bitmap> mCache; public BitmapCache() { int maxSize = 10 * 1024 * 1024; mCache = new LruCache<String, Bitmap>(maxSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getRowBytes(); * bitmap.getHeight(); } }; } @Override public Bitmap getBitmap(String url) { return mCache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { mCache.put(url, bitmap); } } private void getImageByImageLoader() { ImageView iv = (ImageView) findViewById(R.id.iv); RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); String url = "https:\/\/"//www.baidu.com/img/bdlogo.png"; ImageLoader loader=new ImageLoader(queue,new BitmapCache() ); // The first parameter specifies the ImageView control used to display the image // The second parameter specifies the image to be displayed during the loading of the image // The third parameter specifies the image to be displayed when the image fails to load ImageLoader.ImageListener listener=ImageLoader.getImageListener(iv,R.mipmap.ic_launcher,R.mipmap.ic_launcher); // Call the ImageLoader's get() method to load the image // The first parameter is the image URL address // The second parameter is the ImageListener object just obtained // If you want to limit the size of the image, you can also use the overloaded get() method, specifying the maximum width and height of the image allowed, that is, specifying through the third and fourth parameters loader.get(url,listener); }
The third method of loading images
Finally, Volley provides a way to customize ImageView to load images, which can be summarized as
1. Create a RequestQueue object.
2. Create an ImageLoader object.
3. Add a NetworkImageView control to the layout file.
4. Obtain the instance of the control in the code.
5. Set the image address to be loaded.
Step one: Declare the control in the layout
<com.android.volley.toolbox.NetworkImageView android:id="@"+id/network_image_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" />
Step two: Implement loading in the program
public void networkImageView(){ RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); ImageLoader loader=new ImageLoader(queue,new BitmapCache() ); NetworkImageView niv= (NetworkImageView) findViewById(R.id.network_image_view); niv.setDefaultImageResId(R.mipmap.ic_launcher);//Set the image to be displayed when loading niv.setErrorImageResId(R.mipmap.ic_launcher);//Set the image to be displayed when loading fails niv.setImageUrl("https://www.baidu.com/img/bdlogo.png", loader);//Set the URL address of the target image }
4Custom Request
. In practical applications, it is often necessary to integrate HTTP requests with JSON, and Volley exactly supports this kind of method, but we need to customize our own Request, here we use Google's Gson library for integration.
1. Inherit Request class
2. Override parseNetworkResponse to implement the conversion between JSON and entity class, as the entity class is not yet defined, so generics are used
The following JSON string is used below
{"name":"lizhangqu","age":16}
Step 1:
package cn.edu.zafu.http; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.google.gson.Gson; import java.io.UnsupportedEncodingException; /** * Created by lizhangqu on 2015/5/7. */ public class GsonRequest<T> extends Request<T> { private final Response.Listener<T> mListener; private Gson mGson; private Class<T> mClass; public GsonRequest(int method, String url, Class<T> clazz, Response.Listener<T> listener, Response.ErrorListener errorListener) { super(method, url, errorListener); mGson = new Gson(); mClass = clazz; mListener = listener; } public GsonRequest(String url, Class<T> clazz, Response.Listener<T> listener, Response.ErrorListener errorListener) { this(Method.GET, url, clazz, listener, errorListener); } @Override protected Response<T> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(mGson.fromJson(jsonString, mClass), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } } @Override protected void deliverResponse(T response) { mListener.onResponse(response); } }
Step two: Write the test entity class with two fields, one name and one age
package cn.edu.zafu.http; /** * Created by lizhangqu on 2015/5/7. */ public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
Step 3: The method call is the same as StringRequest. As shown below
private void json(){ RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); String url = "http://121.41.119.107/test/index.php"; GsonRequest<Person> request=new GsonRequest<Person>(url, Person.class, new Response.Listener<Person>() { @Override public void onResponse(Person response) { Log.d("TAG",response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); queue.add(request); }
The above is the introduction of the use of the Volley framework for network data requests in Android by the editor. I hope it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time. I also want to express my sincere gratitude to everyone for their support of the Yelling Tutorial website!
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace '#' with '@' when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.