Android最火的框架系列(四)Volley

     其实,本来不想写Volley的,由于前面写了一篇如何使用Eclipse搭建Android服务端的博客,今天,我们尝试用Volley去访问一下。其实,Volley已经不算是很火的网络请求框架了,Volley算是一个比较适合新手的网络请求库。Volley现在在Github上仅有2.3k的star,现在用的多的是Retrofit+okhttp。但是,Volley在某些场景下,使用起来还是挺不错的。今天,主要介绍下Volley的使用以及Volley源码分析。

    首先,Volley的Github地址:https://github.com/google/volley

一.Volley的使用场景

    Volley适合什么样的场景下使用呢?我觉得有如下几点:

    (1)新手从未接触过网络请求框架,那么可以使用Volley。因为Volley的使用非常简单,学习成本比较低。

    (2)数据交互量不大,且通信频繁。Volley非常适合数据量小且交互频繁的场景。

    (3)没有上传和下载文件的需求。因为Volley不支持文件的下载。

二.Volley的导入

    1.下载Volley的jar包放在libs文件夹下面,如下图所示:

2.在volley.jar上右键,选择add as library,如下图所示:

三.Volley的使用

1.get请求

private void getRequest(String address) {

        RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);
        StringRequest stringRequest = new StringRequest(address,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("TTTT", response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TTTT", error.getMessage(), error);
            }
        });
        mQueue.add(stringRequest);
    }

    在需要发送get请求的地方,调用getRequest方法。例如,我这里是去访问我自己搭建的简单Android服务端:

getRequest("http://192.168.1.110:8080/MyAndroidServer/Servers?username=admin&password=admin");

    这里需要注意三点:

    (1)为我们的测试app在AndroidManifest文件中增加网络权限:

<uses-permission android:name="android.permission.INTERNET"/>

    (2)不能使用127.0.0.1:8080,使用自己电脑的ip,可以在命令行窗口输入ipconfig查看自己电脑的ip地址:

    (3)由于我们使用的是局域网访问,因此,要保证电脑和手机处于同一局域网下

    我们测试一下是否访问成功:

    (1)Android Studio输出信息:

    (2)Eclipse服务端输出信息:

2.post请求

    private void getRequest(String address) {

        RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);
        StringRequest stringRequest = new StringRequest(address,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("TTTT", response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TTTT", error.getMessage(), error);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("username", "admin");
                map.put("password", "admin");
                return map;
            }
        };
        mQueue.add(stringRequest);
    }

四.Volley关键源码分析

1.Volley.newRequestQueue    

    使用Volley的时候,我们的第一步操作,往往是先获取一个RequestQueue对象。RequestQueue是什么呢?我们根据名字来猜想一下:请求队列。是的,我们使用Volley的第一步就是去得到一个请求队列:

RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);

    那么,这个请求队列到底是什么,它是如何实现的?毫无疑问,这个方法在Volley这个类中,我们跟踪一下newRequestQueue这个方法:

public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        File cacheDir = new File(context.getCacheDir(), "volley");
        String userAgent = "volley/0";

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

        if (stack == null) {
            if (VERSION.SDK_INT >= 9) {
                stack = new HurlStack();
            } else {
                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
            }
        }

        Network network = new BasicNetwork((HttpStack)stack);
        RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
        queue.start();
        return queue;
    }

    (1)得到一个userAgent,userAgent是什么?可以理解为客户端的名字。userAgent默认是“volley/0”,后通过PackageInfo获取了versionCode,所以,userAgent可能是“volley/1.0"之类的名字。标志着客户端所使用的volley版本。

    (2)获取一个httpStack,HttpStack是什么?而且,如果sdk版本号大于等于9和9以下获取的HttpStack是不一样的。这个想必大家都清楚,Android在使用http请求时,在Android 2.2及以前的版本,使用的是HttpClient,而在Android 2.3及以上版本,使用的是HttpURLConnection。所以呢,这里的HurlStack,它实际上内部是通过HttpUrlConnection来实现的,而HttpClientStack则通过HtttpClient来实现。在这里,我只截取部分源码:

HurlStack:

URL parsedUrl = new URL(url);
        HttpURLConnection connection = openConnection(parsedUrl, request);
        for (String headerName : map.keySet()) {
            connection.addRequestProperty(headerName, map.get(headerName));
        }
        setConnectionParametersForRequest(connection, request);
HttpClientStack:

public HttpClientStack(HttpClient client) {
        mClient = client;
    }

    (3)获取一个NetWork对象,根据传入的HttpStack去处理网络请求,然后获取一个RequestQueue并且调用start方法,我们看一下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并且启动。在源码中,mDispatchers的长度是4:

    /** Number of network request dispatcher threads to start. */
    private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;

    public RequestQueue(Cache cache, Network network, int threadPoolSize,
            ResponseDelivery delivery) {
        mCache = cache;
        mNetwork = network;
        mDispatchers = new NetworkDispatcher[threadPoolSize];
        mDelivery = delivery;
     }

    public RequestQueue(Cache cache, Network network) {
        this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE);
    }

    这意味着什么?当调用了newRequestQueue之后,会有五个分发器(线程)一直在后台运行,不断的等待网络请求的到来,其中四个是缓存线程,一个是网络请求线程。

    获得RequestQueue后,我们需要构建我们需要的请求,例如StringRequest,然后把我们的Request添加到这个请求队列中,我们网络请求所做的工作就完成了。接下来的事情,交给Volley去做。

2.RequestQueue.add

    当我们简单的把我们的request添加到队列后,Volley到底做了什么工作呢?接下来,我们看一下RequestQueue的add方法:

/**
     * Adds a Request to the dispatch queue.
     * @param request The request to service
     * @return The passed-in request
     */
    public Request add(Request request) {
        // Tag the request as belonging to this queue and add it to the set of current requests.
        request.setRequestQueue(this);
        synchronized (mCurrentRequests) {
            mCurrentRequests.add(request);
        }

        // Process requests in the order they are added.
        request.setSequence(getSequenceNumber());
        request.addMarker("add-to-queue");

        // If the request is uncacheable, skip the cache queue and go straight to the network.
        if (!request.shouldCache()) {
            mNetworkQueue.add(request);
            return request;
        }

        // Insert request into stage if there's already a request with the same cache key in flight.
        synchronized (mWaitingRequests) {
            String cacheKey = request.getCacheKey();
            if (mWaitingRequests.containsKey(cacheKey)) {
                // There is already a request in flight. Queue up.
                Queue<Request> stagedRequests = mWaitingRequests.get(cacheKey);
                if (stagedRequests == null) {
                    stagedRequests = new LinkedList<Request>();
                }
                stagedRequests.add(request);
                mWaitingRequests.put(cacheKey, stagedRequests);
                if (VolleyLog.DEBUG) {
                    VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);
                }
            } else {
                // Insert 'null' queue for this cacheKey, indicating there is now a request in
                // flight.
                mWaitingRequests.put(cacheKey, null);
                mCacheQueue.add(request);
            }
            return request;
        }
    }

    很长的一段代码,我总结一下重点的工作:

    (1)把当前的请求添加到当前的请求队列中去

    (2)对请求排序,因为会按照顺序处理请求

    (3)如果请求不支持缓存,那么直接添加到NetWorkQueue。如果请求支持缓存,那么添加到CacheQueue

3.CacheDispatcher.run

    请求默认是支持缓存的,因此,请求默认被加到缓存队列中执行,接下来,我们看一下缓存队列是如何执行的。我们看一下CacheDispatcher的run方法:

public void run() {
        if (DEBUG) VolleyLog.v("start new dispatcher");
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

        // Make a blocking call to initialize the cache.
        mCache.initialize();

        while (true) {
            try {
                // Get a request from the cache triage queue, blocking until
                // at least one is available.
                final Request request = mCacheQueue.take();
                request.addMarker("cache-queue-take");

                // If the request has been canceled, don't bother dispatching it.
                if (request.isCanceled()) {
                    request.finish("cache-discard-canceled");
                    continue;
                }

                // Attempt to retrieve this item from cache.
                Cache.Entry entry = mCache.get(request.getCacheKey());
                if (entry == null) {
                    request.addMarker("cache-miss");
                    // Cache miss; send off to the network dispatcher.
                    mNetworkQueue.put(request);
                    continue;
                }

                // If it is completely expired, just send it to the network.
                if (entry.isExpired()) {
                    request.addMarker("cache-hit-expired");
                    request.setCacheEntry(entry);
                    mNetworkQueue.put(request);
                    continue;
                }

                // We have a cache hit; parse its data for delivery back to the request.
                request.addMarker("cache-hit");
                Response<?> response = request.parseNetworkResponse(
                        new NetworkResponse(entry.data, entry.responseHeaders));
                request.addMarker("cache-hit-parsed");

                if (!entry.refreshNeeded()) {
                    // Completely unexpired cache hit. Just deliver the response.
                    mDelivery.postResponse(request, response);
                } else {
                    // Soft-expired cache hit. We can deliver the cached response,
                    // but we need to also send the request to the network for
                    // refreshing.
                    request.addMarker("cache-hit-refresh-needed");
                    request.setCacheEntry(entry);

                    // Mark the response as intermediate.
                    response.intermediate = true;

                    // Post the intermediate response back to the user and have
                    // the delivery then forward the request along to the network.
                    mDelivery.postResponse(request, response, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mNetworkQueue.put(request);
                            } catch (InterruptedException e) {
                                // Not much we can do about this.
                            }
                        }
                    });
                }

            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
                continue;
            }
        }
    }

    add方法的实现还是比较复杂的。我们梳理一下关键的任务:

    (1)从缓存队列中取出一个请求

    (2)从缓存中检索请求,如果没在缓存中 ,则直接分发给NetWorkDispatcher

    (3)判断缓存是否到期限,如果到期限,则直接分发给NetWorkDispatcher

    (4)如果有一个缓存命中,则解析数据以便响应请求

4.NetworkDispatcher.run

    上面分析了CacheDispatcher的run方法,接下来,我们看一下NetworkDispatcher的run方法:

public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        Request request;
        while (true) {
            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;
                }

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

                // 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) {
                parseAndDeliverNetworkError(request, volleyError);
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
                mDelivery.postError(request, new VolleyError(e));
            }
        }
    }

    做的主要工作如下:

    (1)从队列中取请求

    (2)执行网络请求

    (3)解析请求数据并将请求写入缓存

    (4)返回响应信息

4.NetWork.performRequest

        NetworkDispatcher通过NetWork.performRequest来执行网络请求。NetWork是一个接口,BasicNetwork是具体的实现类。接下来,我们看一下这个方法:

public NetworkResponse performRequest(Request<?> request) throws VolleyError {
        long requestStart = SystemClock.elapsedRealtime();
        while (true) {
            HttpResponse httpResponse = null;
            byte[] responseContents = null;
            Map<String, String> responseHeaders = new HashMap<String, String>();
            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();

                responseHeaders = convertHeaders(httpResponse.getAllHeaders());
                // Handle cache validation.
                if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,
                            request.getCacheEntry().data, responseHeaders, true);
                }

                // Some responses such as 204s do not have content.  We must check.
                if (httpResponse.getEntity() != null) {
                  responseContents = entityToBytes(httpResponse.getEntity());
                } else {
                  // Add 0 byte response as a way of honestly representing a
                  // no-content request.
                  responseContents = new byte[0];
                }

                // if the request is slow, log it.
                long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
                logSlowRequests(requestLifetime, request, responseContents, statusLine);

                if (statusCode < 200 || statusCode > 299) {
                    throw new IOException();
                }
                return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
            } catch (SocketTimeoutException e) {
                attemptRetryOnException("socket", request, new TimeoutError());
            } catch (ConnectTimeoutException e) {
                attemptRetryOnException("connection", request, new TimeoutError());
            } catch (MalformedURLException e) {
                throw new RuntimeException("Bad URL " + request.getUrl(), e);
            } catch (IOException e) {
                int statusCode = 0;
                NetworkResponse networkResponse = null;
                if (httpResponse != null) {
                    statusCode = httpResponse.getStatusLine().getStatusCode();
                } else {
                    throw new NoConnectionError(e);
                }
                VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
                if (responseContents != null) {
                    networkResponse = new NetworkResponse(statusCode, responseContents,
                            responseHeaders, false);
                    if (statusCode == HttpStatus.SC_UNAUTHORIZED ||
                            statusCode == HttpStatus.SC_FORBIDDEN) {
                        attemptRetryOnException("auth",
                                request, new AuthFailureError(networkResponse));
                    } else {
                        // TODO: Only throw ServerError for 5xx status codes.
                        throw new ServerError(networkResponse);
                    }
                } else {
                    throw new NetworkError(networkResponse);
                }
            }
        }
    }

    也是比较长的一个方法,这也是网络请求的一些具体古城。我们一步一步跟着代码和注释分析下关键的流程:

    (1)收集Headers

    (2)处理缓存验证

    (3)记录很慢的网络请求

5.HttpStack.performRequest

    还记得我们最早的时候提到过的HttpStack吗,在上面的代码中,我们又看到了他的身影。接下来,我们看一下,HttpStack.performRequest方法。HttpStack也是一个接口,其实现类则是我们一开始说的HurlStack和HttpClientStack。我们看一下具体的方法:

public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
            throws IOException, AuthFailureError {
        HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
        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);
    }

    上面是HttpClientStack的performRequest方法,我们可以看到一些很常规的操作:获取Headers,获取Params,获取网络超时时间等,最后使用HttpClient调用execute方法去执行一个http请求。好了,终于到了最后执行请求的地方了,我们对于Volley的关键源码分析到此为止。有兴趣的可以看一下HurlStack执行请求的代码,其实前半部分差不多,后半部分有点差别。这也是因为我们一开始说到的,Android2.2及以下版本以及Android2.3及以上版本对执行http请求的不同处理方式,感兴趣的可以自己去研究一下。

五.部分类图

    如下是几部分的类图,仅供参考:

    (1)Request相关的类图:

    (2)Error相关的类图:

    (3)HttpStack相关类图:

    最后,总结一下:分析源码真的是一项很累的工作。自己辞职后有很多的空闲时间,又很喜欢写代码看源码。怎么说呢,没工作比工作都累吧。最近两三周的时间,基本每天都在看源码,写代码,写博客,很累但是也很充实。希望自己能尽快的找到一份满意的工作,到时候估计也没这么多精力写博客到凌晨了。后面,我还会陆陆续续的更新博客。既然选择了做一件事,就要做好!

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个玩游戏的程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值