上篇中有提到NetworkDispatcher是通过mNetwork(Network类型)来进行网络访问的,现在来看一下关于Network是如何进行网络访问的。

Network部分的类图:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAywAAAGbCAIAAACpvIMuAAAgAElEQVR4nO3d25GqShgG0I7HEAjBQCjDmCoTIALDoGq/nTwMxvOgIpcGES80sFb9tWumNypCa3/TIIYLAAA/F+ZeAQCALRLCAABm0A5h//33X3Q57dq1a9euXbt27R9sNxMGADADIQwAYAZCGADADIQwAIAZCGEAADMQwgAAZiCEAQDMYOg6YX8hKKVSqIHXqXbt2rVrX2j70EzYXwiXyz+l1LzVDWEArIAQplTqJYQBrJIQplTqJYQBrJIQplTqJYQBrJIQplTqJYQBrJIQto0q9yGEEEJezr0m6vUSwgBWSQhLu86HLDucX/2vdh3zsCvOcz8XNbWEMIBVenKdsNmHnw3UMY9nqb72e40PYedDFvbl9DU8FVn05n3t6sPlOmHatWvXvsp2M2Ez1qnIQojEo1r7NWmdD1l2KPJQO6R4XSaEELLidDkf7r/tivPtVkV+vZPj/XYhZIey2IX6kpd/l9oCefmvfVeX2jKRzNfXrj5ZZsIAVkkIm6fKvJVyetqrEFadzlXub6HnMRN2zKsk113+0jNnVu5DfryGudqJYp27qt/kms/yY/vp9LWrD5UQBrBKQtjv65jHT5CPtddmws71ltYPoW5ftvJT6+a1ibFzd8nWXXXXv9y/1q7eLiEMYJWEsHnq5Zmw4RDWnbKKhrDzIavuvHvP0btq3a2ZsDlKCANYJSFsxnrtnLBICLvdtjOFNhDC7u3nYheywzlyOLJ3ls45YXOVEAawSkLY7DX46ciBEHabNmudmN9zkLF5kxBClu+7RzObJ+ZX6cqnI2cuIQxglYQwpVIvIQxglVwnTKnUy3XCtGvXrn2V7WbClEq9zIQBrJIQplTqJYQBrJIQpjp1PTffZx6TKSEMYJWEsHTrfPuKoX15uV4KNWTFqWfh61cPfeizikJYYiWEAaySEJZu3UNYyEshbNMlhAGskhCWbl1DWJ7vQ35shLBy//hioexw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Z2rVrj7Z3Q9jTAWlg5IiGsO5wFY1crRi36AGpO5yktt+X2B7tq2Pie/SvhWicevqHR1/Pjy4z/HpZWZ//7Ksmhf62uHYZFpanO7ANvEsOTxL0DUvR9qcPt+gByd/03/D3LNMMd8KBnvxq46UZ0QbueSBpjYmPmyqvmjfZfLA8E0JY98/97kgzPLoIYUzQF8L6XEZHpTGNrRms1goM3/PTO1xBn3+/vGreZPPB8owMYdGMNTzq9C0wZvm+x1pKGU6+oS+E9f0w0M365rQG/m1lu6d/ePT9LIT1lVfNm2w+WJ7owKYMJwn6XggbSE6v/uHRNwPXN6NWfwghbO4utmw2HyyPEGY4WYqBEDY8vTpmJqyvoplsOIR1l7mMm+4SwubuYstm88HyCGGGk6Xo9tVo3OnW+yGsO1v29HCkEPZqedW8yeaD5RHCDCdL8dcTay49p+cPLxn939b9Tzgc2feIT5fve6ztlFfNm9qbL6nrZ2jXrj3a/heC+kYlsn/X1P637Yyy+qq/alLob4trl2EB+BYhbN1lJuxNNh8A3yKErbuEsDfZfAB8ixC27hLC3mTzAfAts5/np75dc3exZbP5AABmIIQBAMxACAMAmIHr4mjXrl27du3atbtOGADANghhAAAzEMIAAGYghAEAzEAIAwCYgRAGADADIQwAYAauE6Zdu3bt2rVr1+46YQAA2yCEAQDMQAgDAJiBEAYAMAMhDABgBkIYAMAMhDAAgBn8Dz1A6TXntTTmAAAAAElFTkSuQmCC" alt="" />

Network有一个实现类BasicNetwork,它有一个mHttpStack的属性,实际的网络请求是由这个mHttpStack来进行的,看BasicNetwork的performRequest()方法,

  @Override
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() == null ? null : 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[];
} // if the request is slow, log it.
long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
logSlowRequests(requestLifetime, request, responseContents, statusLine); if (statusCode < || statusCode > ) {
throw new IOException();
}
return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
}
             //一堆catch...
      }

可以看到,在该方法中,实际是调用了mHttpStack.performRequest(request, headers);来进行网络访问,并对访问结果进行处理,貌似用的是Decorator模式。

如果状态码是304(HttpStatus.SC_NOT_MODIFIED)表示从上次访问后,服务器数据没有改变,则从Cache中拿数据。

【304(未修改)自从上次请求后,请求的网页未修改过。服务器返回此响应时,不会返回网页内容。如果网页自请求者上次请求后再也没有更改过,您应将服务器配置为返回此响应(称为 If-Modified-Since HTTP 标头)。服务器可以告诉客户端自从上次抓取后网页没有变更,进而节省带宽和开销。】

再来看HttpStack部分, HttpStack有两个实现类:HttpClientStack,HurlStack。分别通过HttpClient与HttpURLConnection来进行网络请求。

来看HttpClientStack的performRequest()方法

 @Override
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, );
HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
return mClient.execute(httpRequest);
} /**
* Creates the appropriate subclass of HttpUriRequest for passed in request.
*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
Map<String, String> additionalHeaders) throws AuthFailureError {
switch (request.getMethod()) {
case Method.DEPRECATED_GET_OR_POST: {
// This is the deprecated way that needs to be handled for backwards compatibility.
// If the request's post body is null, then the assumption is that the request is
// GET. Otherwise, it is assumed that the request is a POST.
byte[] postBody = request.getPostBody();
if (postBody != null) {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
HttpEntity entity;
entity = new ByteArrayEntity(postBody);
postRequest.setEntity(entity);
return postRequest;
} else {
return new HttpGet(request.getUrl());
}
}
case Method.GET:
return new HttpGet(request.getUrl());
case Method.DELETE:
return new HttpDelete(request.getUrl());
case Method.POST: {
HttpPost postRequest = new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(postRequest, request);
return postRequest;
}
case Method.PUT: {
HttpPut putRequest = new HttpPut(request.getUrl());
putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(putRequest, request);
return putRequest;
}
case Method.HEAD:
return new HttpHead(request.getUrl());
case Method.OPTIONS:
return new HttpOptions(request.getUrl());
case Method.TRACE:
return new HttpTrace(request.getUrl());
case Method.PATCH: {
HttpPatch patchRequest = new HttpPatch(request.getUrl());
patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(patchRequest, request);
return patchRequest;
}
default:
throw new IllegalStateException("Unknown request method.");
}
}

通过request的mMethod属性来生成相应的HttpUriRequest, 然后通过成员属性mClient(HttpClient类型)的execute()方法来执行网络请求。

接着看HurlStack的performRequest()方法

 @Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
String url = request.getUrl();
HashMap<String, String> map = new HashMap<String, String>();
map.putAll(request.getHeaders());
map.putAll(additionalHeaders);
if (mUrlRewriter != null) {
String rewritten = mUrlRewriter.rewriteUrl(url);
if (rewritten == null) {
throw new IOException("URL blocked by rewriter: " + url);
}
url = rewritten;
}
URL parsedUrl = new URL(url);
HttpURLConnection connection = openConnection(parsedUrl, request);
for (String headerName : map.keySet()) {
connection.addRequestProperty(headerName, map.get(headerName));
}
setConnectionParametersForRequest(connection, request);
// Initialize HttpResponse with data from the HttpURLConnection.
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", , );
int responseCode = connection.getResponseCode();
if (responseCode == -) {
// -1 is returned by getResponseCode() if the response code could not be retrieved.
// Signal to the caller that something was wrong with the connection.
throw new IOException("Could not retrieve response code from HttpUrlConnection.");
}
StatusLine responseStatus = new BasicStatusLine(protocolVersion,
connection.getResponseCode(), connection.getResponseMessage());
BasicHttpResponse response = new BasicHttpResponse(responseStatus);
response.setEntity(entityFromConnection(connection));
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
if (header.getKey() != null) {
Header h = new BasicHeader(header.getKey(), header.getValue().get());
response.addHeader(h);
}
}
return response;
}

也是根据request的mMethod属性来生成相应的HttpURLConnection,通过HttpURLConnection来进行网络请求。

那么什么时候使用HttpClientStack(即使用HttpClient),什么时候使用HurlStack(即使用HttpURLConnection)呢? 来看一个叫做Volley的工具类

 public class Volley {

     /** Default on-disk cache directory. */
private static final String DEFAULT_CACHE_DIR = "volley"; /**
* 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 An {@link HttpStack} to use for the network, or null for default.
* @return A started {@link RequestQueue} instance.
*/
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, );
userAgent = packageName + "/" + info.versionCode;
} catch (NameNotFoundException e) {
} if (stack == null) {
25 if (Build.VERSION.SDK_INT >= 9) {
26 stack = new HurlStack();
27 } else {
28 // Prior to Gingerbread, HttpUrlConnection was unreliable.
29 // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
30 stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
31 }
} Network network = new BasicNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start(); return queue;
} /**
* 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, null);
}
}

在它的新建一个请求队列的方法newRequestQueue(Context context, HttpStack stack)中,如果没有指定stack,则根据Android SDK的版本来决定使用HttpClientStack还是HurlStack。SDK版本大于等于9(9对应的应该是Android2.3-2.3.2 GingerBread)的时候使用的是HurlStack,小于9的时候使用的是HttpClientStack。

在第一篇的RequestManager中,初始化Volley是如下所示代码,所以得知,如果Android版本是2.3或以后的就使用HurlStack, 低于2.3版本的就使用HttpClientStack来进行网络请求。

 public static void init(Context context) {
mRequestQueue = Volley.newRequestQueue(context);
}

至于为什么要这样做,可以参考http://www.eoeandroid.com/thread-314728-1-1.html或原文http://android-developers.blogspot.com/2011/09/androids-http-clients.html(貌似需要翻墙,把内容贴到下面)

总结如下:

1. HttpClient由于API繁多,所以很难在不破坏兼容性的情况下对它进行优化,所以Android团队对它的优化与改进不是很积极。

2. HttpURLConnection因为API简单,所以对它进行升级优化比较容易。

3. 在Froyo之前,HttpURLConnection有一些bug,尤其是对一个可读的InputStream调用close会污染整个连接池,使得只能通过禁用连接池来解决它。

4. 在Gingerbread中,HttpURLConnection会自动地将这个header  Accept-Encoding: gzip 加入请求并处理相应的经过压缩的响应。在Https连接方面也做了一些改进,HttpURLConnection会尝试通过SNI来进行连接, SNI可以使多个Https主机共享一个IP地址。如果连接失败,也能自动重试。

5. 在Ice Cream Sandwich中,增加了响应缓存。

6. 在Froyo或之前的版本中,最好使用HttpClient,因为它bug很少,而HttpURLConnection却有如3中的bug,Gingerbread或以上的版本,则应该使用HttpURLConnection,HttpURLConnection也是Android团队愿意花精力去优化与改进的。

Android’s HTTP Clients

[This post is by Jesse Wilson from the Dalvik team. —Tim Bray]

Most network-connected Android apps will use HTTP to send and receive data. Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.

Apache HTTP Client

DefaultHttpClient and its sibling AndroidHttpClient are extensible HTTP clients suitable for web browsers. They have large and flexible APIs. Their implementation is stable and they have few bugs.

But the large size of this API makes it difficult for us to improve it without breaking compatibility. The Android team is not actively working on Apache HTTP Client.

HttpURLConnection

HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applications. This class has humble beginnings, but its focused API has made it easy for us to improve steadily.

Prior to Froyo, HttpURLConnection had some frustrating bugs. In particular, calling close() on a readable InputStream couldpoison the connection pool. Work around this by disabling connection pooling:

private void disableConnectionReuseIfNecessary() {
    // HTTP connection reuse which was buggy pre-froyo
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
        System.setProperty("http.keepAlive", "false");
    }
}

In Gingerbread, we added transparent response compression. HttpURLConnection will automatically add this header to outgoing requests, and handle the corresponding response:

Accept-Encoding: gzip

Take advantage of this by configuring your Web server to compress responses for clients that can support it. If response compression is problematic, the class documentation shows how to disable it.

Since HTTP’s Content-Length header returns the compressed size, it is an error to use getContentLength() to size buffers for the uncompressed data. Instead, read bytes from the response until InputStream.read() returns -1.

We also made several improvements to HTTPS in Gingerbread. HttpsURLConnection attempts to connect with Server Name Indication (SNI) which allows multiple HTTPS hosts to share an IP address. It also enables compression and session tickets. Should the connection fail, it is automatically retried without these features. This makes HttpsURLConnection efficient when connecting to up-to-date servers, without breaking compatibility with older ones.

In Ice Cream Sandwich, we are adding a response cache. With the cache installed, HTTP requests will be satisfied in one of three ways:

  • Fully cached responses are served directly from local storage. Because no network connection needs to be made such responses are available immediately.

  • Conditionally cached responses must have their freshness validated by the webserver. The client sends a request like “Give me /foo.png if it changed since yesterday” and the server replies with either the updated content or a304 Not Modified status. If the content is unchanged it will not be downloaded!

  • Uncached responses are served from the web. These responses will get stored in the response cache for later.

Use reflection to enable HTTP response caching on devices that support it. This sample code will turn on the response cache on Ice Cream Sandwich without affecting earlier releases:

private void enableHttpResponseCache() {
    try {
        long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
        File httpCacheDir = new File(getCacheDir(), "http");
        Class.forName("android.net.http.HttpResponseCache")
            .getMethod("install", File.class, long.class)
            .invoke(null, httpCacheDir, httpCacheSize);
    } catch (Exception httpResponseCacheNotAvailable) {
    }
}

You should also configure your Web server to set cache headers on its HTTP responses.

Which client is best?

Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.

For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward.

[Android]Volley源码分析(四)的更多相关文章

  1. Android Volley源码分析

    今天来顺手分析一下谷歌的volley http通信框架.首先从github上 下载volley的源码, 然后新建你自己的工程以后 选择import module 然后选择volley. 最后还需要更改 ...

  2. [Android]Volley源码分析(五)

    前面几篇通过源码分析了Volley是怎样进行请求调度及请求是如何被实际执行的,这篇最后来看下请求结果是如何交付给请求者的(一般是Android的UI主线程). 类图:

  3. [Android]Volley源码分析(三)

    上篇看了关于Request的源码,这篇接着来看下RequestQueue的源码. RequestQueue类图:

  4. [Android]Volley源码分析(二)

    上一篇介绍了Volley的使用,主要接触了Request与RequestQueue这两个类,这篇就来了解一下这两个类的具体实现. Request类图:

  5. Volley源码分析(四)NetWork与ResponseDelivery工作原理

    这篇文章主要分析网络请求和结果交付的过程. NetWork工作原理 之前已经说到通过mNetWork.performRequest()方法来得到NetResponse,看一下该方法具体的执行流程,pe ...

  6. [Android]Volley源码分析(一)

    一. 如何使用Volley? 1. 首先定义一个RequestManager类,用来在Android程序启动时对Volley进行初始化.RequestManager为单例类,因为只有在程序启动时调用, ...

  7. Android Volley源码分析及扩展

    转载请标明出处: http://www.cnblogs.com/why168888/p/6681232.html 本文出自:[Edwin博客园] Volley 介绍 Android系统中主要提供了两种 ...

  8. Volley源码分析(2)----ImageLoader

    一:imageLoader 先来看看如何使用imageloader: public void showImg(View view){ ImageView imageView = (ImageView) ...

  9. Appium Android Bootstrap源码分析之启动运行

    通过前面的两篇文章<Appium Android Bootstrap源码分析之控件AndroidElement>和<Appium Android Bootstrap源码分析之命令解析 ...

随机推荐

  1. ant+findbugs 扫描代码生成报告

    1. 下载安装ant.findbugs 下载ant.findbugs最新压缩包解压到本地磁盘合适位置,比如: D:\Program Files\apache-ant-1.9.7 D:\Program ...

  2. $是对string.Format的简化

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  3. 查看数据库表的数据量和SIZE大小的脚本修正

    在使用桦仔的分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间)的脚本时,遇到下面一些错误 这个是因为这些表的Schema是Maint,而不是默认的dbo,造成下面这段SQ ...

  4. .NET应用架构设计—适当使用活动记录模式代替领域模型模式

    阅读目录: 1.背景介绍 2.简单介绍领域模型模式.活动记录模式 3.活动记录模式的简单示例及要点 4.总结 1.背景介绍 对软件开发方法论有兴趣的博友应该发现最近“领域驱动设计”慢慢的被人发现被人实 ...

  5. C库函数使用与总结之字符串处理函数

    1. memcpy(拷贝内存内容) [头文件]#include <string.h> [函数原型]void *memcpy(void *dest, const void *src, siz ...

  6. Log4J基础详解及示例大全

    去年这个时候,为做软件工程的大作业就详细学过Log4J的用法了,时隔一年想要在新的项目中好好使用一下的时候,发现几乎全忘了,悲催啊-- 再上网查资料,总是不能找到一篇符合我的口味,拿来就能轻松上手,方 ...

  7. Java 对象初始化

      对象A的创建过程: 1. 构造器实际上是静态方法.当首次创建对象A 或者 A类的静态方法/静态域首次被访问时,Java解释器查找类路径,以定位     A.class文件.(当程序创建第一个对类的 ...

  8. monkeyrunner之测试结果判断(八)

    monkeyrunner的功能脚本编写完成之后,我们就需要对结果进行判断,判断结果是否为我们预期的结果值.下面我们主要讲述2种方式判断结果. 方式一.monkeyrunner截图对比 这是monkey ...

  9. 单元测试实战 - Junit测试

    一.对加法函数进行测试 1.实例化被测单元(方法):类名 实例名=new 类名([参数]) 2.调用被测单元,对比预期值和输出值(实际值): 在没有junit测试工具的情况下,我们要进行如下的测试代码 ...

  10. iOS与Html5和JS之间的交互---学习笔记五

    首先采用的框架是WebViewJavascriptBridge,采用这套框架可以方便的使iOS与JS交互 一. 流程图(主要介绍思路) 二.iOS端如何使用 首先导入#import "Web ...