zoukankan      html  css  js  c++  java
  • Volley——网络请求

      Volley作为当年Google在2013年的Google I/O上的重点,是一个相当给力的框架。它从设计模式上来说,非常具有扩展性,也比较轻巧。关于Volley的使用,网上介绍的很多了,不再赘述。现在,我将记录我阅读Volley源码的过程,来学习Volley的设计思想和其中的一些小技巧。

      值的一提的是,新版的gradle已经支持:  

    compile 'com.android.volley:volley:1.0.0'

      这样导入Volley了。

      从最简单的例子看起:

    RequestQueue queue;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            queue = Volley.newRequestQueue(this);
            final StringRequest request = new StringRequest("https://www.baidu.com/",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            ((TextView) findViewById(R.id.test_textview_id)).setText(response);
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
    
                        }
                    });
            findViewById(R.id.test_btn_id).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    queue.add(request);
                }
            });
        }

      可以看到,一个简单的Volley的http请求,只需要三步,建立Request队列--->建立Request请求--->将请求加入Request队列。

      今天就只看这三步是怎么运作的。

      我们先来看看queue = Volley.newRequestQueue(this);

        public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
            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);
    
            RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
            queue.start();
    
            return queue;
        }

      从体来说这个方法,做了以下几件事:获取userAgent、创建HttpStack、创建NetWork、创建并启动RequestQueue。。

      获取userAgetnt的方法比较简单 userAgent = packageName + "/" + info.versionCode; 一目了然。

      接着创建HttpStack和NetWork比较复杂,会单独记录。

      最后会创建一个RequestQueue,作为请求队列。并且在初始化时,请求队列会直接启动。

      接下来,我们看一下RequestQueue的代码。我们先从构造方法开始阅读:

        /**
         * Creates the worker pool. Processing will not begin until {@link #start()} is called.
         *
         * @param cache A Cache to use for persisting responses to disk
         * @param network A Network interface for performing HTTP requests
         * @param threadPoolSize Number of network dispatcher threads to create
         * @param delivery A ResponseDelivery interface for posting responses and errors
         */
        public RequestQueue(Cache cache, Network network, int threadPoolSize,
                ResponseDelivery delivery) {
            mCache = cache;
            mNetwork = network;
            mDispatchers = new NetworkDispatcher[threadPoolSize];
            mDelivery = delivery;
        }

      在初始化时,RequestQueue对4个成员赋了值。缓存、NetWork、网络分发线程队列和网络响应分发接口。 

      下面我们看看在初始化Volley初始化时,第一个会调用的方法start()

        /**
         * Starts the dispatchers in this queue.
         */
        public void start() {
            stop();  // Make sure any currently running dispatchers are stopped.
            // Create the cache dispatcher and start it.
            mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
            mCacheDispatcher.start();
    
            // Create network dispatchers (and corresponding threads) up to the pool size.
            for (int i = 0; i < mDispatchers.length; i++) {
                NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
                        mCache, mDelivery);
                mDispatchers[i] = networkDispatcher;
                networkDispatcher.start();
            }
        }

       上面的代码比较简洁。首先调用stop();关于stop():

      

        public void stop() {
            if (mCacheDispatcher != null) {
                mCacheDispatcher.quit();
            }
            for (int i = 0; i < mDispatchers.length; i++) {
                if (mDispatchers[i] != null) {
                    mDispatchers[i].quit();
                }
            }
        }

      它就是通过遍历,结束了线程中的所有任务。

      我们可以在NetworkDispatcher.java中找到相关实现

    public void quit() {
        mQuit = true;
        interrupt();
    }
    public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            while (true) {
                long startTimeMs = SystemClock.elapsedRealtime();
                Request<?> request;
                try {
                    // Take a request from the queue.
                    request = mQueue.take();
                } catch (InterruptedException e) {
                    // We may have been interrupted because it was time to quit.
                    if (mQuit) {
                        return;
                    }
                    continue;
                }
            ......
            }    
    }    

      继续看start方法:

      

        /**
         * Starts the dispatchers in this queue.
         */
        public void start() {
            stop();  // Make sure any currently running dispatchers are stopped.
            // Create the cache dispatcher and start it.
            mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
            mCacheDispatcher.start();
    
            // Create network dispatchers (and corresponding threads) up to the pool size.
            for (int i = 0; i < mDispatchers.length; i++) {
                NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
                        mCache, mDelivery);
                mDispatchers[i] = networkDispatcher;
                networkDispatcher.start();
            }
        }

      stop之后,就会启动CacheDispatcher和NetworkDispatcher。

      关于NetworkDispatcher中start()方法的实现,NetworkDispatcher继承了Thread,所以看start()其实是看run方法:

        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            while (true) {
                long startTimeMs = SystemClock.elapsedRealtime();
                Request<?> request;
                try {
                    // Take a request from the queue.
                    request = mQueue.take();
                } catch (InterruptedException e) {
                    // We may have been interrupted because it was time to quit.
                    if (mQuit) {
                        return;
                    }
                    continue;
                }
    
                try {
                    request.addMarker("network-queue-take");
    
                    // If the request was cancelled already, do 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 304 AND we delivered a response already,
                    // we're 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(), response.cacheEntry);
                        request.addMarker("network-cache-written");
                    }
    
                    // Post the response back.
                    request.markDelivered();
                    mDelivery.postResponse(request, response);
                } catch (VolleyError volleyError) {
                    volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                    parseAndDeliverNetworkError(request, volleyError);
                } catch (Exception e) {
                    VolleyLog.e(e, "Unhandled exception %s", e.toString());
                    VolleyError volleyError = new VolleyError(e);
                    volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                    mDelivery.postError(request, volleyError);
                }
            }
        }

      代码比较长,我们分段阅读。

            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            while (true) {
                long startTimeMs = SystemClock.elapsedRealtime();
                Request<?> request;
                try {
                    // Take a request from the queue.
                    request = mQueue.take();
                } catch (InterruptedException e) {
                    // We may have been interrupted because it was time to quit.
                    if (mQuit) {
                        return;
                    }
                    continue;
                }

      设置线程优先级为标准后台线程,然后进入死循环。虽然这一段代码没有什么实质的实现,但是却很重要,它基本确立了这个线程的工作模式。这个线程在while(true)的死循环中,每次循环有一次停止线程和一次暂停线程的机会,暂停在前。

      mQueue是个阻塞型队列。每次循环会在这个队列里取一个请求,如果mQueue为空,取不到请求了,线程就会卡死在这里,这就是暂停的机会,等到mQueue加入请求时,线程又会重新跑起来。通过这样的设计,我们后面发起http请求,只需要往mQueue里加入请求就好了。当调用interrupt方法时,循环就会进入catch分支,然后判断是否真的要取消,所以我们在quit()方法中,看到它的实现是先将mQuit置为true,然后调用interrupt来结束这个线程。

                try {
                    request.addMarker("network-queue-take");
    
                    // If the request was cancelled already, do not perform the
                    // network request.
                    if (request.isCanceled()) {
                        request.finish("network-discard-cancelled");
                        continue;
                    }
    
                    addTrafficStatsTag(request);

      如果请求被取消,则调用请求的finish方法,进入下一轮循环。 然后加入流量标记。我们可以看到addTrafficStatsTag

        @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        private void addTrafficStatsTag(Request<?> request) {
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
        }

      我们可以对这个网络请求加上标记,方便调式时知晓它的流量使用情况。

                    // Perform the network request.
                    NetworkResponse networkResponse = mNetwork.performRequest(request);
                    request.addMarker("network-http-complete");
    
                    // If the server returned 304 AND we delivered a response already,
                    // we're done -- don't deliver a second identical response.
                    if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                        request.finish("not-modified");
                        continue;
                    }

      接着便了Network执行它的performRequest方法,方法的具体实现,将在后面阅读。通过这个方法,我们处理了网络请求,取得了响应——NetworkResponse。下面的一个判断语句,注释解释得很清楚。如果我们的请求返回304,并且我们已经分发过这个响应了。我们将不再处理响应,结束这次循环,开始下一轮。同时执行request.finish的方法。如果没有304,那么我们还要考虑如何处理响应。

                    // 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(), response.cacheEntry);
                        request.addMarker("network-cache-written");
                    }

       这里,进行解析网络响应,获得响应——Response。根据配置,如果需要缓存,则将响应的内容缓存在mCache中。

                    // Post the response back.
                    request.markDelivered();
                    mDelivery.postResponse(request, response);

      最后,根据请求,分析网络响应。 

      至此,我们将volley的网络请求及处理流程基本走通了一遍。后面的文章中,将仔细分析一些Volley对于网络请求的一些处理细节。

    Done

  • 相关阅读:
    MySQL binlog 组提交与 XA(分布式事务、两阶段提交)【转】
    一致性哈希算法原理
    【MySQL (六) | 详细分析MySQL事务日志redo log】
    Replication基础(六) 复制中的三个线程(IO/SQL/Dump)
    硬盘基本知识(磁头、磁道、扇区、柱面
    MySQL架构总览->查询执行流程->SQL解析顺序
    Redis之AOF重写及其实现原理
    MySQL binlog中的事件类型
    linux(mac) 编译安装MySQL
    写给自己看的Linux运维基础(四)
  • 原文地址:https://www.cnblogs.com/fishbone-lsy/p/5426166.html
Copyright © 2011-2022 走看看