github编辑

Volley源码分析

Volley的基本流程就是:

  1. 创建一个RequestQueue

  2. 在RequestQueue中创建缓存线程和请求线程

  3. 在请求线程中不断的执行请求

  4. 执行完请求之后通过handler发送到主线程

创建RequestQueue

/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context) {
    return newRequestQueue(context, (BaseHttpStack) null);
}
    /**
     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
     *
     * @param context A {@link Context} to use for creating the cache dir.
     * @param stack A {@link BaseHttpStack} to use for the network, or null for default.
     * @return A started {@link RequestQueue} instance.
     */
    public static RequestQueue newRequestQueue(Context context, BaseHttpStack stack) {
      //这个构造函数负责构建
        BasicNetwork network;
        if (stack == null) {
            if (Build.VERSION.SDK_INT >= 9) {
                network = new BasicNetwork(new HurlStack());
            } else {
                // Prior to Gingerbread, HttpUrlConnection was unreliable.
                // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
                // At some point in the future we'll move our minSdkVersion past Froyo and can
                // delete this fallback (along with all Apache HTTP code).
                String userAgent = "volley/0";
                try {
                    String packageName = context.getPackageName();
                    PackageInfo info =
                            context.getPackageManager().getPackageInfo(packageName, /* flags= */ 0);
                    userAgent = packageName + "/" + info.versionCode;
                } catch (NameNotFoundException e) {
                }

                network =
                        new BasicNetwork(
                                new HttpClientStack(AndroidHttpClient.newInstance(userAgent)));
            }
        } else {
            network = new BasicNetwork(stack);
        }

        return newRequestQueue(context, network);
    }

HttpStack是对网络请求的封装,HurlStack使用的是HttpUrlConnectionHttpClientStack使用的是HttpClient。可以通过代码看到,Android Api9以上使用HttpUrlConnection以下使用HttpClient进行请求。

![](https://github.com/malinkang/AndroidNote/tree/d1597593e5ee17033c5f2c57144388148a98c9f3/network/images/httpstack.png)

RequestQueue构造函数

在RequestQueue中创建缓存线程和请求线程

RequestQueuestart方法

CacheDispatcherNetworkDispatcher都继承自Thread,分别是缓存线程和网络请求线程。

CacheDispatcher

NetworkDispatcher

执行完请求之后通过handler发送到主线程

ExecutorDelivery负责将请求结果传递给主线程

总结

VolleyRetrofit是类似的框架,是对网络请求客户端的封装,让请求更加便捷。内部可以选择使用HttpUrlConnectionOkhttp或者HttpClient

参考

最后更新于