volley源代码解析(七)--终于目的之Response<T>

时间:2022-12-08 12:54:14

在上篇文章中,我们终于通过网络,获取到了HttpResponse对象

HttpResponse是android包里面的一个类。然后为了更高的扩展性,我们在BasicNetwork类里面看到。Volley将其包装成一个Volley自己的对象NetworkResponse

另外,在BasicNetwork类中我们也注意到。对HttpResponse包装成NetworkResponse的过程中,使用HttpResponse的Inputstream,将数据保存在一个byte[]数组中。

BasicNetwork代码片段:

 // Some responses such as 204s do not have content.  We must check.
if (httpResponse.getEntity() != null) {//返回响应主体
responseContents = entityToBytes(httpResponse.getEntity());//将主体转换byte[]形式
} else {//没有返回内容
// Add 0 byte response as a way of honestly representing a
// no-content request.
responseContents = new byte[0];
}

这样可能造成的一个问题,就是内存溢出。这也是Volley之所以不能用来下载大文件的原因,由于byte[]是保存在内存中的。

好了,以下让我们来看NetworkResponse的源代码

     /**
     * The HTTP status code.
     * http状态码
     */
    public final int statusCode;     /**
     * Raw data from this response.
     * 数据
     */
    public final byte[] data;     /**
     * Response headers.
     * 响应头
     */
    public final Map<String, String> headers;     /**
     * True if the server returned a 304 (Not Modified).
     * 网页是否改动.304
     */
    public final boolean notModified;     /**
     * Network roundtrip time in milliseconds.
     * 响应时间
     */
    public final long networkTimeMs; /**
* Creates a new network response.
* @param statusCode the HTTP status code
* @param data Response body
* @param headers Headers returned with this response, or null for none
* @param notModified True if the server returned a 304 and the data was already in cache
* @param networkTimeMs Round-trip network time to receive network response
*/
public NetworkResponse(int statusCode, byte[] data, Map<String, String> headers,
boolean notModified, long networkTimeMs) {
this.statusCode = statusCode;
this.data = data;
this.headers = headers;
this.notModified = notModified;
this.networkTimeMs = networkTimeMs;
}

本质上没有什么特别的。仅仅是将HttpResponse的内容。简单地转移到NetworkResponse中

接下来,在响应分发过程中,request负责把NetworkResponse又包装成Response<T>对象

NetworkDispatcher代码片段:

// Parse the response here on the worker thread. 解析网络响应到本地
Response<? > response = request.parseNetworkResponse(networkResponse);

至于怎么解析。不同的request应该有自己的实现。

可能看到这里大家有些迷糊,原因是我们找回了之前类的一些代码

在前面的解析中,我们总是忽略这些片段,默觉得全都是Response。由于在前面的过程中。理解Response之间的不同会给我们理解核心代码带来困扰,所以我们都跳过了。

如今源代码解析接近尾声,我们再回头看各种各样的Response就豁然开朗了。

httpStack获得的是HttpResponse,由于HttpResponse是android的内置类,我们使用起来很不灵活(由于我们希望response都是一样的,不管是从缓存中取的还是网络请求的)

依据上述原因,我们有了NetworkResponse。这个代表网络请求对应。这是Volley的自己定义类,这样我们使用起来就灵活了(理论上缓存也应该有一个CacheResponse,然而Volley没有这样设计)。更加重要的一点是NetworkResponse中的byte[]数组保存了网络数据(前面说过。这是造成内存溢出的原因)

最后。为了统一全部的Response,我们将NetworkResponse(理论上另一个CacheResponse)又封装成了了Response<T>

OK,Volley解析基本到这里就结束了。

接下来的文章。将会带大家看一下Volley最后的一部分小花絮,关于图片载入的部分。

另外,我还会依据自己的理解,带大家来改造Volley,使之有很多其它更完好的功能。