Volley 2, an open-source android network framework

Source: Internet
Author: User
Tags unsupported

The previous article briefly introduced the use of volley. This article will continue to share with you the use of volley.

In fact, I forget a very important thing. I believe it is also a confusing place for many people who first know volley, that is, where to start learning, learn volley, and use volley, maybe Google or Baidu is most likely to use a simple demo or translation of volley. If you are familiar with it, it may be easy to understand it, but it is still a little difficult for me to wait for a cainiao. Although the level is limited, I will try my best to follow my understanding of volley during this period.


1. Deployment of volley

As mentioned above, we will not directly create a volley Request queue object in Activiy, because we only need one object. If this is not the case, what should we do? Here is a suggestion. First, create a project structure:


The idea is as follows: we initialize volley in the application. Then get this object through the static method, you can use it in all places, the key code is as follows (from: https://github.com/ogrebgr ):

/*** This code comes from here: https://github.com/ogrebgr ** @ author ttdevs */public class VolleyQueue {private static RequestQueue mRequestQueue; private static ImageLoader mImageLoader; private VolleyQueue () {}/*** initialize our request queue. There is a BitmapLruCache, which is the image Cache Policy ** @ param context */static void init (Context context) {mRequestQueue = Volley. newRequestQueue (context); int memClass = (ActivityManager) context. getSystemService (Context. ACTIVITY_SERVICE )). getMemoryClass (); // Use 1/8th of the available memory for this memory cache.int cacheSize = 1024*1024 * memClass/8; mImageLoader = new ImageLoader (mRequestQueue, New BitmapLruCache (cacheSize);} public static RequestQueue getRequestQueue () {if (mRequestQueue! = Null) {return mRequestQueue;} else {throw new IllegalStateException ("RequestQueue not initialized") ;}} public static ImageLoader getImageLoader () {if (mImageLoader! = Null) {return mImageLoader;} else {throw new IllegalStateException ("ImageLoader not initialized ");}}}
In this way, we can use it wherever we want.


2. After the User-Defined request obtains the Request queue object through the first step, we can send the request freely ~~ Simple GET requests have been shown before. The following is a POST request and a custom request object. Before that, let's take a look at the structure of the volley source code. Here we also look at two figures: authorization/J0tTIpc/Iv7TSu8/authorization + slrwo294rvh09c63366so/W + qGjCrWxxOO88rWlsum/authorization + authorization = "brush: java;"> public class CustomReqeust extends Request {Private final Listener MListener; public CustomReqeust (int method, String url, Listener Listener, ErrorListener errorListener) {super (method, url, errorListener); mListener = listener;} @ Overrideprotected Response ParseNetworkResponse (NetworkResponse response) {// TODO Auto-generated method stubreturn null;} @ Overrideprotected void deliverResponse (String response) {// TODO Auto-generated method stub }}Let's analyze these lines of code. The first is the constructor. Through super, we find that in the constructor we need to provide three parameters: method, url, and errorListener, which respectively mean the request method, that is, POST/GET; request URL; callback listener when an error occurs. The StringRequest constructor has a Listener. Listener. You should know through the demo above that it is used to process the request results. Of course, we need this in most cases, so we add it. This is complete. There are two methods that must be implemented. What is this? Let's take a look at the implementation of the two methods in StringRequest:
    @Override    protected void deliverResponse(String response) {        mListener.onResponse(response);    }    @Override    protected Response
      
        parseNetworkResponse(NetworkResponse response) {        String parsed;        try {            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));        } catch (UnsupportedEncodingException e) {            parsed = new String(response.data);        }        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));    }
      

protected void deliverResponse(String response) {}
Send a response, and pass the HTTP response result through the successful listener set during initialization.
protected Response
      
        parseNetworkResponse(NetworkResponse response){}
      
Through the name, we guess it is to parse the network response. For the StringRequest class source code analysis, we roughly conclude that it should be based on the HTTP header encoding to parse the HTTP packet body. When we process special or custom HTTP requests, we can resolve the HTTP packet body here.

After talking about this, we still haven't talked about how to implement http post requests, because we haven't talked about how to set POST request parameters.

After reading several request class subclasses in volley source code, we can find the following code in the JsonRequest class:
   /**     * Returns the raw POST or PUT body to be sent.     *     * @throws AuthFailureError in the event of auth failure     */    @Override    public byte[] getBody() {        try {            return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);        } catch (UnsupportedEncodingException uee) {            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",                    mRequestBody, PROTOCOL_CHARSET);            return null;        }    }
Yes, you guessed it. He is the method for processing our request parameters. Here we organize the parameters to be passed and convert them into byte arrays. In this way, we can start to implement our own custom requests. Below is a simple and complete example for your reference:
Public class CustomReqeust extends Request
      
       
{/** Http Request Encoding Method */private static final String PROTOCOL_CHARSET = "UTF-8"; private Listener
       
        
MListener; private String mUserName; public CustomReqeust (String url, String userName, Listener
        
         
Listener, ErrorListener errorListener) {super (Method. POST, url, errorListener); mUserName = userName; mListener = listener;} @ Overrideprotected Response
         
          
ParseNetworkResponse (NetworkResponse response) {String parsed; try {parsed = new String (response. data, HttpHeaderParser. parseCharset (response. headers);} catch (UnsupportedEncodingException e) {parsed = new String (response. data);} return Response. success (parsed, HttpHeaderParser. parseCacheHeaders (response);} @ Overrideprotected void deliverResponse (String response) {mListener. onResponse (response);} @ Ov Erridepublic byte [] getBody () {try {return mUserName = null? Null: mUserName. getBytes (PROTOCOL_CHARSET);} catch (UnsupportedEncodingException uee) {VolleyLog. wtf ("Unsupported Encoding while trying to get the bytes of % s using % s", mUserName, PROTOCOL_CHARSET); return null ;}}}
         
        
       
      
You do not need to paste the call code, but you still need to paste it (the URL here is still www.baidu.com ):
private void customRequest() {CustomReqeust request = new CustomReqeust(URL, "CustomVolley", new Listener
      
       () {@Overridepublic void onResponse(String arg0) {Toast.makeText(getApplicationContext(), arg0, Toast.LENGTH_LONG).show();Log.d("onResponse", arg0);}}, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {Toast.makeText(getApplicationContext(), arg0.toString(), Toast.LENGTH_LONG).show();Log.d("onErrorResponse", arg0.toString());}});mQueue.add(request);}
      
Because there is no test server, you can simply capture packets and check the results as follows:
We can see that our request is correct. So far, we have completed the implementation of custom requests.
3. The summary can be customized. For more HTTP Request Parameters, you can start with several Request subclasses, such as setting the ContentType type and getRetryPolicy () in the JsonRequest class (). After learning about these things, you will find that volley is really high-end. Of course, there are still many details not mentioned, such as canceling a request and setting request timeout. These details will be shared with you if you analyze the source code. I will share with you some time on how volley loads images. From the next article, I will share with you the entire volley architecture. Finally, you are welcome to speak out when there are any mistakes.
Note: The current time is, and the code is not everything. After this time, the less the code, the better. More important things are waiting for you. Please note that Mark may be about to lose his five-year relationship. Finally, I wish all single programmers could find their own ......





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.