Android in about volley use (10) understanding of request and reponse

Source: Internet
Author: User

We know that in the network HTTP communication, there will be a request, the same, there will certainly be a response, and we volley in the use of Requestqueue to add a request, we must first create a requester object, For example, Stringrequest,jsonobjectrequest and Imagerequest, respectively, the following are Jsonrequest and Imagerequest in the previous demo:

Jsonobjectrequest:

    Public jsonobjectrequest (String URL, jsonobject jsonrequest, listener<jsonobject> Listener,            Errorlistener Errorlistener) {

Imagerequest:

    Public imagerequest (String URL, response.listener<bitmap> Listener, int maxWidth, int maxheight,            

The volley provides a basic request abstract class, as follows:

Public abstract class Request<t> implements Comparable<request<t>> {

In this class, you define some basic parameter variables in the request, such as

Method:

    /**     * Request method of this request.  Currently supports GET, POST, PUT, DELETE, HEAD, OPTIONS,     * TRACE, and PATCH.     */    private final int mmethod;
It has the following values:

    /**     * Supported request methods.     *    /public interface Method {        int deprecated_get_or_post =-1;        int GET = 0;        int POST = 1;        int PUT = 2;        int DELETE = 3;        int HEAD = 4;        int OPTIONS = 5;        int TRACE = 6;        int PATCH = 7;    }

URL in the request:

    /** URL of this request. */    private final String Murl;

A Errolistener,

    /** Listener interface for errors. */    private final Response.errorlistener Merrorlistener;

There are other parameters, such as shouldcache (whether cache is required), tag (category tag), etc., and the following two abstract methods are provided in the request, which must be implemented by subclasses:

    /**     * Subclasses must implement this to parse the RAW network response     * and return an appropriate response type. This method would be is     * called from a worker thread.  The response is not being delivered     * if you return null.     * @param response response from the network     * @return The parsed response, or null in the case of an error    */ Abstract protected response<t> parsenetworkresponse (Networkresponse Response);

    /**     * Subclasses must implement this to perform delivery for the parsed     * response to their listeners.  The given response is guaranteed to     * was non-null; responses that fail to parse was not delivered.     * @param response The parsed response returned by     * {@link #parseNetworkResponse (networkresponse)}    */ Abstract protected void Deliverresponse (T response);

Each subclass must implement two methods,

1) parsenetworkresponse

When getting to response from the network, how to parse the corresponding request, which is analyzed by the respective request, such as Jsonobjectrequest:

    @Override    protected response<jsonobject> parsenetworkresponse (Networkresponse Response) {        try {            String jsonstring =                new String (Response.data, Httpheaderparser.parsecharset (response.headers));            Return response.success (New Jsonobject (jsonstring),                    httpheaderparser.parsecacheheaders (Response));        } catch (Unsupportedencodingexception e) {            return Response.error (new ParseError (e));        } catch (Jsonexception je) {            return Response.error (New ParseError (JE));        }    

Again, for example in Imagerequest:

    @Override    protected response<bitmap> parsenetworkresponse (Networkresponse Response) {        //Serialize All Decode on a global lock to reduce concurrent heap usage.        Synchronized (sdecodelock) {            try {                return Doparse (response);            } catch (OutOfMemoryError e) {                VOLLEYLOG.E ("Caught OOM for%d byte image, url=%s", Response.data.length, GetUrl ());                Return Response.error (New ParseError (e));}}}    

In the Doparse, the picture is actually processed, as follows:

    Private response<bitmap> Doparse (Networkresponse Response) {byte[] data = Response.data;        Bitmapfactory.options decodeoptions = new Bitmapfactory.options ();        Bitmap Bitmap = null;            if (Mmaxwidth = = 0 && Mmaxheight = = 0) {decodeoptions.inpreferredconfig = Mdecodeconfig;        Bitmap = Bitmapfactory.decodebytearray (data, 0, Data.length, decodeoptions);            } else {//If We have an resize this image, first get the natural bounds.            Decodeoptions.injustdecodebounds = true;            Bitmapfactory.decodebytearray (data, 0, Data.length, decodeoptions);            int actualwidth = Decodeoptions.outwidth;            int actualHeight = Decodeoptions.outheight;            Then compute the dimensions we would ideally as to decode.            int desiredwidth = Getresizeddimension (Mmaxwidth, Mmaxheight, ActualWidth, actualHeight); int desiredheight = Getresizeddimension (mmaxhEight, Mmaxwidth, ActualHeight, actualwidth);            Decode to the nearest power of both scaling factor.            Decodeoptions.injustdecodebounds = false;            TODO (Ficus): Do we need this or are it okay since API 8 doesn ' t support it?            Decodeoptions.inpreferqualityoverspeed = Prefer_quality_over_speed;            Decodeoptions.insamplesize = Findbestsamplesize (ActualWidth, ActualHeight, Desiredwidth, desiredheight);            Bitmap Tempbitmap = bitmapfactory.decodebytearray (data, 0, Data.length, decodeoptions);            If necessary, scale down to the maximal acceptable size.                    if (Tempbitmap! = null && (Tempbitmap.getwidth () > Desiredwidth | |                        Tempbitmap.getheight () > Desiredheight)) {bitmap = Bitmap.createscaledbitmap (Tempbitmap,                Desiredwidth, Desiredheight, true);            Tempbitmap.recycle (); } else{bitmap = Tempbitmap;        }} if (bitmap = = null) {return response.error (new ParseError (Response));        } else {return response.success (bitmap, Httpheaderparser.parsecacheheaders (Response)); }    }

So, if we customize a request, we are going to implement our own logic, such as acquiring video, and then decoding the data.

In the above method implementation, we can see that the last is to return a response object through the Response.success method, and this response object is how to use it, it is necessary to see the Deliverresponse method below.

2) Deliverresponse

In a networkdispatcher thread, when the data is fetched from the network and parsed by the requested Parsenetworkresponse method, a Reponse object is returned, at this time, The executor is called to post the request back to the main thread, as follows:

Mdelivery.postresponse (request, response);

The Postresponse method in Mdelivery is actually another new thread that calls the Deliverresponse method of request, in the Executordelivery class:

public void Postresponse (request<?> Request, response<?> Response, Runnable Runnable) {        Request.markdelivered ();        Request.addmarker ("Post-response");        Mresponseposter.execute (New responsedeliveryrunnable (Request, Response, runnable));    }

In the Run method of the Responsedeliveryrunnable class, we can see:

            Deliver a normal response or error, depending.            if (mresponse.issuccess ()) {                mrequest.deliverresponse (mresponse.result);            } else {                Mrequest.delivererror (Mresponse.error);            }

Let's look at the Deliverresponse method in Stringrequest and imagerequest:

Private final response.listener<bitmap> Mlistener; @Override    protected void Deliverresponse (Bitmap Response) {        mlistener.onresponse (response);    }
We can see that In fact, it is called a Response.listener class Onresponse method, and in fact this listener, we create the request when the implementation, and passed in, such as the previous demo in the creation of Jsonobjectrequest and imagerequest when:

Imagerequest imgrequest = new Imagerequest (imgurl,new response.listener<bitmap> () {@Overridepublic void Onresponse (Bitmap arg0) {//TODO auto-generated method Stubimageview.setimagebitmap (arg0);}, Config.argb_ 8888, new Errorlistener () {@Overridepublic void Onerrorresponse (Volleyerror arg0) {Imageview.setimageresource ( R.drawable.ic_launcher);});

As implemented in the new Reponse.listener method above, it is clear that the reason for this is that only the caller knows how to handle the data that is parsed by the request.

And from here, we can also know that in the Reponse class, such an interface is defined, such as the following, is the definition of the response class in volley:

public class Response<t> {    /** Callback interface for delivering parsed responses. */Public    interface Liste ner<t> {        /** called when a response is received. *        /public void Onresponse (T response);    }

In addition to the definition of this interface, there is a definition of the Errorlistener interface is not listed. In addition, response class in the storage of cacheentry and other information, relatively speaking, because the definition of such listener interface, response class is relatively simple.

Well, here's a summary:

1) When a request is created, a response.listener is set as a parameter variable for the requested, and then the Add method of the Requestqueue is called into the queue.

2) Requests in the queue are networkdispatcher to communicate with the network (Cachedispatcher if there is a cache).

3) When the request results come back, requests will first call the Parsenetworkresponse method for different processing depending on the request type, such as Json,image.

4) When the request is parsed, the resulting Reponse object will be processed by a new thread from the Responsedelivery class, calling the listener in step 1).

End.


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.