Volley core source code analysis (1)

The basic process of Http request

  Volley's initialization RequestQueue requestQueue = Volley.newRequestQueue(context),

what is returned is a RequestQueue object, the function of this object will be discussed below. Now entering the inside of the method,

you

  public static RequestQueue newRequestQueue(Context context) {
        return newRequestQueue(context, null);
    }

  public static RequestQueue newRequestQueue(Context context, HttpStack stack)
    {
    return newRequestQueue( context, stack, -1);
    }
  
public static RequestQueue newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) {
        File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

        String userAgent = "volley/0";
        try {
            String packageName = context.getPackageName();
            PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
            userAgent = packageName + "/" + info.versionCode;
        } catch (NameNotFoundException e) {
        }

        if (stack == null) {
            if (Build.VERSION.SDK_INT >= 9) {
                stack = new HurlStack();
            } else {
                // Prior to Gingerbread, HttpUrlConnection was unreliable.
                // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
            }
        }

       Network network = new BasicNetwork(stack);



At this point we look at the HttpClientStack class, what does this class do?

public class HttpClientStack implements HttpStack

HttpStack is an interface with only one method:

public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError;

[align=left][/align] The
parameter is a Request The object of <?> This is a generic type, and its role will be discussed below.
Then this method translated into Chinese is: execute the request.

The specific implementation of performRequest in HttpClientStack is as follows:

@Override
    public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
            throws IOException, AuthFailureError {
        HttpUriRequest httpRequest = createHttpRequest(request,
        addHeaders(httpRequest, additionalHeaders);
        addHeaders(httpRequest, request.getHeaders());
        onPrepareRequest(httpRequest);
        HttpParams httpParams = httpRequest.getParams();
        int timeoutMs = request.getTimeoutMs();
        // TODO: Reevaluate this connection timeout based on more wide-scale
        // data collection and possibly different for wifi vs. 3G.
        HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
        HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
        return mClient.execute(httpRequest);
    }


protected final HttpClient mClient;

Until this time, I found out that Volley uses the apache Http Client framework by default. I remember seeing an article a long time ago saying that the Android development team recommends using the HttpUrlConnection in the java.net package as the method of network requests, which is optimized for the android platform. , but I don't know why HttpClient is still used by default in Volley?

Let's take a look at the Network interface;

public NetworkResponse performRequest(Request<?> request) throws VolleyError;

There is still only one method to execute the request.

In the constructor of the implementation class BasicNetwork, HttpStack is taken as a parameter.

@Override
    public NetworkResponse performRequest(Request<?> request) throws VolleyError {
        long requestStart = SystemClock.elapsedRealtime();
        while (true) {
            HttpResponse httpResponse = null;
            byte[] responseContents = null;
            Map<String, String> responseHeaders = Collections .emptyMap();
            try {
                // Gather headers.
                Map<String, String> headers = new HashMap<String, String>();
                addCacheHeaders(headers, request.getCacheEntry());
                httpResponse = mHttpStack.performRequest(request, headers);
                StatusLine statusLine = httpResponse. getStatusLine();
                int statusCode = statusLine.getStatusCode();

                  .....
}

Seeing here, we seem to understand that volley's calling sequence for http requests is:

Network ----> HttpStack----> HttpClient


If the reader Carefully, you will find that the existing network execution process does not support attributes such as uploading files.
When Volley initializes the request queue, there is an overloaded method:
public static RequestQueue newRequestQueue(Context context, HttpStack stack )
    {
    return newRequestQueue(context, stack, -1);
    }
   
Then to implement more complex network requests, you only need to implement your own HttpStack flexibly in the
performRequest() method to meet the requirements.



Volley's Request object


Reading source code we find that
public abstract class Request<T> implements Comparable<Request<T>>

Request is a generic abstract class and is comparable.

So why implement the Comparable interface?

My understanding is to avoid duplicate requests.


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;
    }


The Method interface in Request defines the supported Http request methods.

abstract protected Response<T> parseNetworkResponse(NetworkResponse response);
This is an abstract method, which must be implemented to implement a custom request. Such as GsonRequest, ImageRequest and so on.

The getPostParams() method must be rewritten to send a Post request: @Deprecated

protected
    Map<String, String> getPostParams() throws AuthFailureError {
        return getParams();
    }


At this point, the process of Volley's network request and the analysis of the source code come to an end.



  The next section request queue RequestQueue  http://f303153041.iteye.com/blog/2281350

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326969269&siteId=291194637