我们看到Network接口只有一个实现类BasicNetwork,而HttpStack有两个实现类。

BasicNetwork这个类是toolbox工具箱包里的,实现了Network接口。

先来看下Network这个interface,performRequest(Request*)执行一个请求,以一个Request为参数,返回一个

NetworkResponse 。
public interface Network {
/**
* Performs the specified request.执行这个请求
* @param request Request to process//待处理的请求
* @return A {@link NetworkResponse} with data and caching metadata; will never be null
* 返回一个请求结果,不会为空
* @throws VolleyError on errors
*/
public NetworkResponse performRequest(Request<?> request) throws VolleyError;
}

BasicNetwork实现了Network接口,我们来看下UML图。

再来看下它的构造函数,两个参数HttpStack和ByteArrayPool,这两个参数就是主要的成员变量。

 /**
* 带一个默认大小的ByteArrayPool缓冲池
* @param httpStack HTTP stack to be used
*/
public BasicNetwork(HttpStack httpStack) {
// If a pool isn't passed in, then build a small default pool that will give us a lot of
// benefit and not use too much memory.
//如果一个池没有通过,将建立一个小的默认缓存池,这样会给我们带来很大的益处,不需要耗费很多内存
this(httpStack, new ByteArrayPool(DEFAULT_POOL_SIZE));
} /**
* 主构造方法BasicNetwork(HttpStack*,ByteArrayPool*)
* @param httpStack HTTP stack to be used
* @param pool a buffer pool that improves GC performance in copy operations
*/
public BasicNetwork(HttpStack httpStack, ByteArrayPool pool) {
mHttpStack = httpStack;
mPool = pool;
}

再看看哪个方法用到了mHttpStack,就是在实现Network接口的performRequest()方法,并且mHttpStack有个跟Network接口同名的方法,这才是真正执行请求的方法,也是直接传入请求返回响应。

而mPool是在entityToBytes()这个方法中用到,顾名思义这个方法就是把HttpEntity转换为bytes数据,而这个缓存池就是为便捷转换数据格式。

再详细看下最重要的方法performRequest(),代码中均以加上注释,见解有误望读者们见谅和请教。

/**
* @title performRequest执行各种Request请求并以NetworkResponse的形式返回结果
* @param Request
* @return NetworkResponse
* @throws VolleyError
* 定义:{@link Network#performRequest(Request)}
* 被调:{@link NetworkDispatcher#run()}
*
*/
@Override//NetworkDispatcher的run()方法中调用
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
long requestStart = SystemClock.elapsedRealtime();//开始请求时间
while (true) {
HttpResponse httpResponse = null;//apache的请求结果
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);//去调用mHttpStack的实现方法执行请求
StatusLine statusLine = httpResponse.getStatusLine();//获取http状态线
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);
} //把HttpEntity转化为byte[]数据
responseContents = entityToBytes(httpResponse.getEntity());
// if the request is slow, log it.//如果请求很慢,就打印出来看一下
long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
logSlowRequests(requestLifetime, request, responseContents, statusLine);//打印 //连接正常但是返回无内容,抛出IO异常
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) {
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) {//Bad URL
throw new RuntimeException("Bad URL " + request.getUrl(), e);
} catch (IOException e) {//IO异常
int statusCode = 0;
NetworkResponse networkResponse = null;
if (httpResponse != null) {
statusCode = httpResponse.getStatusLine().getStatusCode();
} else {//如果没有返回httpResponse,就说明没连接
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);//只有状态码为5XX才抛出服务器异常
}
} else {//网络异常
throw new NetworkError(networkResponse);
}
}
}
}

A:先是通过mHttpStack把请求执行并且获取它的响应结果,根据HttpStatus做出各种判断。

B:然后再把httpResponse的Entity转化为ByteArray,并处理各种发生的异常。

C:最后的过程是这样的:通过Volley创建一个RequestQueue请求队列,当这个队列开始运作的时候会启动NetworkDispatcher这个工作线程,而BasicNetwork的performRequest()的方法就在NetworkDispatcher线程run()方法中调用,然后通过mHttpStack的performRequest()方法获取一个networkResponse,在NetworkDispatcher线程把这个networkResponse转化为期望的数据类型,比如Response<String>,Response<Json>,Response<Bitmap>。

谷歌Volley网络框架讲解——Network及其实现类的更多相关文章

  1. 谷歌Volley网络框架讲解——HttpStack及其实现类

    前两篇已经对网络请求流程已经梳理了个大概,这次我们着重看一下HttpStack和它的其实现类.我们之前在Network篇讲过它仅有一个实现类,而今天我们讲的HttpStack有两个实现类. 其中Htt ...

  2. 谷歌Volley网络框架讲解——BasicNetwork类

    谷歌Volley网络框架讲解——BasicNetwork类 这个类是toolbox工具箱包里的,实现了Network接口. 先来看下Network这个interface,performRequest( ...

  3. 谷歌Volley网络框架讲解——第一篇

    自从公司新招了几个android工程师后,我清闲了些许.于是就可以有时间写写博客,研究一些没来的研究的东西. 今年的谷歌IO大会上,谷歌推出了自己的网络框架——Volley.不久前就听说了但是没有cl ...

  4. 谷歌Volley网络框架讲解——网络枢纽

    研究了这么久的Volley,愈来愈发现这个框架的精美和人性化.比起民间一些框架强很多,一开始总是盲人摸象找不到头绪,现在终于有些明朗了.Volley其实就是一个请求队列的代理类,我们看下UML. 这就 ...

  5. Volley网络框架的使用

    Volley的特点:   使用网络通信更快.更简单 Get/Post网络请求网络图像的高效率异步请求 可以对网络请求的优先级进行排序处理 可以进行网络请求的缓存 可以取消多级别请求 可以和Activi ...

  6. Volley网络框架完全解析(使用篇)

    在Android中,网络请求无非就这两种:HttpURLConnection和HttpClient( Apache),我们在使用时一般都会对它们进行一系列的封装,但是这过程不免有些繁琐,所以,Goog ...

  7. Volley网络框架完全解析(实战篇)

    好了,今天就通过一个瀑布流demo,来使用Volley框架请求网络图片. 前言: 我们使用NetworkImageView显示图片: 1.因为该控件可以自动的管理好请求的生命周期,当与父控件detac ...

  8. Volley网络框架完全解析(缓存篇)

    在上一篇中讲完了Volley框架怎么使用,那么这篇就来讲讲Volley框架的缓存机制 我们看Volley内部源码发现: Volley框架内部自己处理了DiskBasedCache硬盘缓存,但是没有处理 ...

  9. Android网络框架源码分析一---Volley

    转载自 http://www.jianshu.com/p/9e17727f31a1?utm_campaign=maleskine&utm_content=note&utm_medium ...

随机推荐

  1. java- ★学习资源★

    何静媛: http://blog.csdn.net/hejingyuan6/article/category/2367993 孤傲苍狼-java基础总结: http://www.cnblogs.com ...

  2. spring boot 自学笔记(四) Redis集成—Jedis

    上一篇笔记Reddis集成,操作Redis使用的是RedisTemplate,但实际中还是有一大部分人习惯使用JedisPool和Jedis来操作Redis, 下面使用Jedis集成示例. 修改Red ...

  3. skynet1.0阅读笔记2_skynet的消息投递skynet.call

    为了了解 skynet.call 的调用过程,需要先看看 skynet的队列是如何把包分到不同工作线程的.看下图 查看 global_queue 的skynet_globalmq_push和skyne ...

  4. HBase在搜狐内容推荐引擎系统中的应用

    转自:http://www.aboutyun.com/thread-7297-1-1.html Facebook放弃Cassandra之后,对HBase 0.89版本进行了大量稳定性优化,使它真正成为 ...

  5. php 添加数据库的几种方法

    最简单的 <?php $con = mysql_connect("localhost","root","root"); if (!$c ...

  6. stos

    add <?php /* 添加脚本 参数:u=用户名 v=城市名 为用户添加城市标签 */ header("Content-Type:text/html; charset=utf-8& ...

  7. php -- php控制linux关机、重启、注销

        php 里面有个 system(exec) 方法, 可以调用系统命令.     重启先建立一个脚本(比喻 /root/reboot_server.sh ),重启用的.//路径可随便,但最少必须 ...

  8. par函数的ann 参数-控制图片的注释信息

    ann 参数控制图片的x轴和y轴标签以及标题是否显示 默认值为TRUE, 所以图片有对应的信息时,会显示出来,代码示例 plot(1:5, 1:5, main = "title", ...

  9. dom元素改变监听

    function domChange(domId, callback) { // select the target node var target = document.getElementById ...

  10. 感谢各位亲们的大力支持,免费的HTML5学习课程《HTML5网页开发实例具体解释》连载已经结束了!

    感谢各位亲们的大力支持,免费的HTML5学习课程<HTML5网页开发实例具体解释>连载已经结束了.  有兴趣的读者能够看我的博客,也能够看以下的链接逐个学习: 当里个当.免费的HTML5连 ...