The volley framework in Android is used to request network data _android

Source: Internet
Author: User

The problem: The Android SDK HttpClient and httpurlconnection two requests to handle the complex operation of the network, but when the application is more complex, we need to write a lot of code to deal with many things: image caching, request scheduling, etc.;

Solution: Volley was born to solve these problems, and it was presented in the 2013 Google I/O Conference: Making Android more convenient and easy to use network operations, abstracting details of implementations such as the underlying HTTP client, and allowing developers to focus and produce restful Request. In addition, volley executes all requests asynchronously on different threads to avoid blocking the main thread.

Volley can be said to be the advantages of asynchttpclient and Universal-image-loader set in one, can be as simple as the asynchttpclient of 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 substantial adjustment, it is designed to be very suitable for the amount of data, but the network operation of frequent communication, and for large amounts of data network operations, such as downloading files, volley performance will be very bad

1. What are the characteristics of volley?

Automatically schedule network requests

Multiple Concurrent Network Connections

Maintain consistency of disk and memory responses by using a standard HTTP caching mechanism

Support Request Priority

A powerful API that supports cancellation requests to cancel a single request or multiple

Easy customization

Robustness: Facilitates proper updating of the UI and access to data

Includes debugging and tracking tools

2. Requestqueue and Request in volley

Requestqueue the request queue used to execute the request

Requests are used to construct a request object

There are several main types of request objects:

A. The body of the stringrequest response is a string

B. jsonarrayrequest send and receive JSON arrays

C. jsonobjectrequest send and receive JSON objects

D. imagerequest send and receive image

3, the use of volley steps:

(1) Create an Android project and import the volley jar package

(2) How the Get is requested:

Create 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 the Request object
stringrequest request=new stringrequest (URL, new response.listener<string> () {
/**
* Request Successful Result
* @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 for access errors, showing 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);

(3) How the POST request is:

Make it a POST request by specifying the request method, and then Request.Method.POST the request parameters getparams the method. When a POST request is made, volley attempts to invoke the Getparams () method in the Stringrequest parent class--request to get the post parameter.

Create 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 succeeded ============" +response);
Response.errorlistener () {
@Override public
void Onerrorresponse (volleyerror error) {
log.e ("tag", " Request succeeded ============ "+error";
}
) {
/**
* Rewrite the Getparams method to set the parameters, post the method of adding parameters
* * *
@Override
protected map<string, string> Getparams () throws Authfailureerror {
hashmap<string, string> params = new hashmap<string,string> (); C20/>params.put ("__version", "1.0.1.1300");
Params.put ("__plat", "Android");
return params;
}
;
Requestqueue.add (Request);

(3) How to load pictures:

The first way to load a picture

Requestqueue Requestqueue = volley.newrequestqueue (context);
String img = datas.getimg ();
The third fourth parameter is used to specify the maximum width and height of the allowed picture, if the specified network picture width or height is greater than the maximum value here, the picture will be compressed, specified as 0 will mean that no matter how large the picture, will not be compressed.
//The fifth parameter is used to specify the color properties
of the picture 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 way to load pictures

In fact, the function of loading pictures far more than these, using Imageloader can achieve the cache of pictures, you can also filter duplicate links to avoid sending duplicate requests

The use of Imageloader is summarized in the following steps

1. Create a Requestqueue object.

2. Create a Imageloader object.

3. Get a Imagelistener object.

4. Call the Imageloader get () method to load a picture on the network.

Inherits Imagecache, uses LruCache to implement caching public class Bitmapcache implements Imageloader.imagecache {private lrucache<string,
Bitmap> Mcache; Public Bitmapcache () {int maxSize = ten * 1024 * 1024; mcache = new lrucache<string, bitmap> (maxSize) {@Override PR
otected 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, Bi
TMap 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 that is used to display the picture//second parameter specifies the picture that is displayed during the loading of the picture//third parameter specifies the picture to display when the picture is loaded Imageloader.imagelistener listener=
Imageloader.getimagelistener (Iv,r.mipmap.ic_launcher,r.mipmap.ic_launcher); Call IMAgeloader get () method to load picture///The first parameter is the URL of the picture//The second parameter is the Imagelistener object you just acquired//if you want to limit the size of the picture, you can also use the overload of the Get () method.
Specifies the maximum width and height allowed for the picture, that is, the Loader.get (Url,listener) is specified by the third fourth parameter; }

The third way to load pictures

Finally, volley provides a custom ImageView to load a picture, which can be summarized as

1. Create a Requestqueue object.

2. Create a Imageloader object.

3. Add a Networkimageview control to the layout file.

4. Gets the instance of the control in code.

5. Set the picture address to load.

Step One: We 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 the load 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 picture displayed in the load
niv.seterrorimageresid (r.mipmap.ic_launcher); /Set the picture
Niv.setimageurl ("https://www.baidu.com/img/bdlogo.png", loader) displayed when the load fails;//Set the URL address of the destination picture
}

4. Custom Request

In practical applications, it is often necessary to integrate HTTP requests with JSON, and volley is supporting this approach, but we need to customize the request, where we use Google's Gson library for integration.

1. Inherit Request class

2. Rewrite the parsenetworkresponse, implement JSON and entity class conversion, because the entity class is undecided, so the use of generics
The following JSON string is used below

{' name ': ' Lizhangqu ', ' age ': 16}

Step One:

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; priva
Te 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> PARSENETW Orkresponse (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 test entity classes, two fields one name 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 three: The calling method is the same as the 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) {
}
}); C13/>queue.add (request);
}

The above is a small set to introduce the Android volley framework to request the use of network data, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.