Android advanced-Volley-4.Network source code

Source: Internet
Author: User

Android advanced-Volley-4.Network source code

Volley's core structure is as follows:

Today, we mainly look at Network problems:

Network overall function Introduction: by implementing the Network interface class (BasicNetwork), execute the Request retrieved from ReqeuestQueue and return the completed result as NetworkResponse.

Test code:

 

btnTest.setOnClickListener(new OnClickListener() {             @Override            public void onClick(View arg0) {                // TODO Auto-generated method stub                 new Thread() {                    @Override                    public void run() {                        StringRequestrequest = newStringRequest(                                "http://www.youku.com",null,null);                        NetworkResponser = newNetworkResponse(null);                        BasicNetworknetwork = newBasicNetwork(newHurlStack());                        try {                            r= network.performRequest(request);                            Stringstr = newString(r.data);                            Log.i("msg", str);                        }catch(Exception e) {                            // TODO Auto-generated catch block                            for (int i = 0; i < 100; ++i)                                Log.e("ERROR","ERROR");                        }                    }                }.start();             }        });


 

1. HurlStack. java & HttpStack. java

Main functions: HurlStack implements the initiate mrequest in the HttpStack interface. It uses HttpUrlConnection to execute the incoming Request and return HttpResponse.

Class diagram:

Function Analysis:

1.1 constructor:

 

public HurlStack() {        this(null);   }    /**    * @param urlRewriter Rewriter to use for request URLs    */   public HurlStack(UrlRewriter urlRewriter) {        this(urlRewriter, null);   }    /**    * @param urlRewriter Rewriter touse for request URLs    * @param sslSocketFactory SSL factory to use for HTTPS connections    */   public HurlStack(UrlRewriter urlRewriter, SSLSocketFactorysslSocketFactory) {        mUrlRewriter = urlRewriter;       mSslSocketFactory = sslSocketFactory;   }

 

Assign values to member variables.

1.2 initiate mrequest:

 

public HttpResponse performRequest(Request
  request,Map
 
   additionalHeaders)            throws IOException,AuthFailureError {…}
 

Function: parse the Request parameter and return HttpResponse.

Associated functions: openConnection, setConnectionParametersForRequest, entityFromConnection

Execution Process: Obtain the url in the Request, execute the openConnection function to obtain HttpURLConnection, parse the Request through setConnectionParametersForRequest, and set the parameters of HttpURLConnection. Encapsulate the obtained content as HttpEntity through entityFromConnection, store it in the Response (the Response type here is BasicHttpResponse) to be returned, and finally return Response.

1.3 entityFromConnection:

 

private static HttpEntity entityFromConnection(HttpURLConnectionconnection){…}

 

Function: return an HttpEntity Based on the given HttpURLConnection. HttpEntity is an interface, which uses BasicHttpEntity. The returned HttpEntity contains the information in HttpURLConnection: Content), Content Length (ContentLength), Encoding method (Encoding), content type (ContentType)

Join function: None

Execution Process: omitted

1.4 createConnection:

 

protected HttpURLConnection createConnection(URL url) throwsIOException {        return(HttpURLConnection) url.openConnection();    }

 

Function: Enable HttpURLConnection according to the URL.

Join function: None

Execution Process: omitted

1.5 openConnection:

 

private HttpURLConnection openConnection(URL url, Request
 request) throws IOException{…}

 

Function: Enable HttpURLConnection with parameters.

Associated Function: createConnection

Execution Process: Call createConnection to open the HttpURLConnection of the specified URL, and then set the connection timeout value based on the parameters in the Request, and set the user cache not used (connection. setUseCaches (false);), set read from connection. setDoInput (true );). If you are using the https protocol, you also need to set the SSLSocketFactory used when this instance is connected to the socket.

1.6 setConnectionParametersForRequest:

 

static void setConnectionParametersForRequest(HttpURLConnectionconnection,            Request
  request)throws IOException, AuthFailureError {…}

 

Function: sets the Connection method for the Request, including Get, Post, and Delete.

Join function: None

Execution Process: omitted

1.7 addBodyIfExists:

 

private static void addBodyIfExists(HttpURLConnection connection,Request
  request) throws IOException, AuthFailureError {…}

 

Function :?

Association function :?

Execution Process :?

2. ByteArrayPool. java

Main function: ByteArrayPool is the collection pool of byte arrays. It is used to recycle byte arrays, reducing memory allocation and collection. An ArrayList sorted from small to large is used as the cache for byte [], and an ArrayList attribute sorted by time is used to clean up elements when the cache is full.

Class diagram:


Function Analysis:

2.1 Constructor

 

public ByteArrayPool(int sizeLimit) {      mSizeLimit = sizeLimit;  }

 

Sets the Maximum Cache byte size in the Pool.

2.2 getBuf:

 

public synchronized byte[] getBuf(int len) {…}

 

Function: Obtain byte [] with a length not less than len, traverse the cache, find the first byte [] with a length greater than the input parameter len, and return; if no suitable byte [] is found, a new response is returned.

Join function: None

Execution Process: omitted

2.3 returnBuf:

Function: recycles used byte [] and inserts byte [] into the cache in ascending order based on the byte [] length.

Associated Function: trim

Execution Process: omitted

2.4 trim:

Function: When the cached byte exceeds the preset size, delete the earliest byte [] in the FIFO order.

Join function: None

Execution Process: omitted

3. BasicNetwork. java & Network. java

Main function: Call HttpStack to process the Request and convert the HttpResponse returned by HttpStack to NetworkResponse (in volley, ResponseDelivery transmits NetworkResponse ).

Class diagram:

Function Analysis:

3.1 Constructor

 

public BasicNetwork(HttpStack httpStack) {        // If a pool isn'tpassed in, then build a small default pool that will give us a lot of        // benefit and not usetoo much memory.        this(httpStack, newByteArrayPool(DEFAULT_POOL_SIZE));    }     /**     * @param httpStack HTTPstack to be used     * @param pool a bufferpool that improves GC performance in copy operations     */    publicBasicNetwork(HttpStack httpStack, ByteArrayPool pool) {        mHttpStack =httpStack;        mPool = pool;    }

 

3.2 initiate mrequest:

Function: Use the classes that implement the HttpStack interface, such as HurlStack. First parse the Request to the HttpResponse type, and then encapsulate it into the NetworkResponse type for return.

Associated functions: addCacheHeaders and entityToBytes

Execution Process: omitted

3.3 logSlowRequests:

Function: if the network request is too long or the DEBUG switch is enabled, the log message is printed.

Join function: None

Execution Process: omitted

3.4 attemptRetryOnException:

Function: This function is called when the connection times out and authentication fails. There is a retryPolicy parameter used to set a retry policy.

Associated functions: some functions in the Request

Execution Process: Get the retry policy and retry request. getRetryPolicy (). retry (exception). In the request, addMarker

3.5 addCacheHead:

Function: get cached data

Join function: None

Execution Process: If no cached data is returned directly, add it to Map In headers, the header is used to store cached data.

3.6 logError:

Function: print the error message.

Join function: None

Execution Process: omitted

3.7 entityToBytes:

Function: parse HttpEntity and convert its data to byte [] type.

Correlated functions: some functions in ByteArrayPool

Execution Process: None

3.8 convertHeaders:

Function: converts the Header [] type to Map.

Join function: None

Execution Process: omitted

 

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.