[Android] Volley source Analysis (iii) Network

Source: Internet
Author: User

If you crossing carefully read my previous article, actually the network this piece is just a little function supplement. Let's take a look at the core processing logic of Networkdispatcher:

<span style= "FONT-SIZE:18PX;"                >while (True) {try {//Take a request from the queue.            Request = Mqueue.take ();                } catch (Interruptedexception e) {//We may have been interrupted because it is time to quit.                if (mquit) {return;            } continue;                } try {request.addmarker ("Network-queue-take");                If the request was cancelled already, does not perform the//network request.                    if (request.iscanceled ()) {request.finish ("network-discard-cancelled");                Continue                } addtrafficstatstag (Request);                Perform the network request.                Networkresponse networkresponse = mnetwork.performrequest (request);                Request.addmarker ("Network-http-complete"); If the server returned 3Delivered a response already,//we have done--don ' t deliver a second identical response. if (networkresponse.notmodified && request.hashadresponsedelivered ()) {Request.finish                    ("not-modified");                Continue                }//Parse The response here on the worker thread.                response<?> Response = Request.parsenetworkresponse (networkresponse);                Request.addmarker ("Network-parse-complete");                Write to cache if applicable.                Todo:only Update cache metadata instead of entire record for 304s. if (Request.shouldcache () && response.cacheentry! = null) {Mcache.put (Request.getcachekey (), R                    Esponse.cacheentry);                Request.addmarker ("Network-cache-written");                }//Post the response back.                Request.markdelivered (); Mdelivery. Postresponse (Request, response);            } catch (Volleyerror volleyerror) {parseanddelivernetworkerror (request, volleyerror);                } catch (Exception e) {volleylog.e (E, "unhandled Exception%s", e.tostring ());            Mdelivery.posterror (Request, new Volleyerror (e)); }}</span>
we see the difference between Networkdispatcher and Cachedispatcher
<span style= "FONT-SIZE:18PX;" >                Addtrafficstatstag (Request);                Perform the network request.                Networkresponse networkresponse = mnetwork.performrequest (request);                Request.addmarker ("Network-http-complete");</span>
Addtrafficstatstag (Request), the method used to optimize the network channel, does not belong to the focus of our conversation. We know that mnetwork through the httpstack to achieve the network request, we first look at Hurlstack.

<span style= "FONT-SIZE:18PX;" > @Override public httpresponse performrequest (request<?> Request, map<string, string>        Additionalheaders) throws IOException, authfailureerror {String url = request.geturl ();        hashmap<string, string> map = new hashmap<string, string> ();        Map.putall (Request.getheaders ());        Map.putall (additionalheaders);            if (murlrewriter! = null) {String rewritten = Murlrewriter.rewriteurl (URL);            if (rewritten = = null) {throw new IOException ("URL blocked by rewriter:" + URL);        } URL = rewritten;        } URL parsedurl = new URL (URL);        HttpURLConnection connection = OpenConnection (parsedurl, request);        For (String HeaderName:map.keySet ()) {Connection.addrequestproperty (Headername, Map.get (headername));        } setconnectionparametersforrequest (connection, request); Initialize HttpResponse with Data from the HttpURLConnection.        ProtocolVersion protocolversion = new ProtocolVersion ("HTTP", 1, 1);        int responsecode = Connection.getresponsecode ();            if (Responsecode = =-1) {//-1 is returned by Getresponsecode () if the response code could isn't be retrieved.            Signal to the caller that something is wrong with the connection.        throw new IOException ("Could not retrieve response code from HttpURLConnection."); } statusline responsestatus = new Basicstatusline (ProtocolVersion, Connection.getresponsecode (), con        Nection.getresponsemessage ());        Basichttpresponse response = new Basichttpresponse (responsestatus);        Response.setentity (Entityfromconnection (connection)); For (entry<string, list<string>> header:connection.getHeaderFields (). EntrySet ()) {if (header.get    Key () = null) {Header h = new Basicheader (Header.getkey (), Header.getvalue (). Get (0));            Response.AddHeader (h);    }} return response; }</span>

Hurlstack is the httpurlconnection way to request data. At the same time, it has heard the interface Urlrewriter Murlrewriter, to implement the redirection of the URL. Hurlstack returned HttpResponse to the upper Networkdispatcher.httpclientstack the same as we do not look. Of course we also see the cachedispatcher and Networkdispatcher codes, but they are minor flaws. Because of the request.iscancel these aspects of the judgment can be used in the form of a template method to unify.

Networkdispatcher through the network to obtain HttpResponse, still with the same as Cachedispacher with request for packaging:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >Response<?> Response = Request.parsenetworkresponse (networkresponse);                Request.addmarker ("Network-parse-complete");</span></span>
Finally, determine if the request requires the cache to be placed in the cache buffer pool if necessary:

<span style= "FONT-SIZE:18PX;" >if (Request.shouldcache () && response.cacheentry! = null) {                    mcache.put (Request.getcachekey (), Response.cacheentry);                    Request.addmarker ("Network-cache-written");                } </span>
then the basic flow of networkdispatcher is gone. In the next chapter, we will provide a convenient API for volley for us to see volley in combination with source code.


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.