Android有两套http的API,刚开始使用网络编程时多少有些迷惑到底用哪个好呢?其实孰优孰劣无需再争论,google已经指出HttpUrlConnection是Android更优的选择,并在SDK文档中引用了博客(需要代理访问)http://android-developers.blogspot.com/2011/09/androids-http-clients.html来阐述各自的优缺点。国内也有些博客大致翻译了上面的内容,并对了一些测试,可惜测试不严密,某博客甚至得出HttpUrlConnection的下载速度快几倍的结论,其实并没有公平反映出二者的下载速度。

  虽然我已经使用过HttpUrlConnection实现了一个轻量级http引擎用于下载,但是好奇心还是促使我写了一个测试程序用于比较二者的性能。由于HttpClient仅仅是一个接口,所以我选用了其实现类DefaultHttpClient和HttpUrlConnection做比较,方法很简单,分别下载同一个文件10次,然后计算耗时的平均值,测试代码片段如下:

     @Override
public void onClick(View v)
{
if (v.equals(mTestHttpClientBtn))
{
new Thread(new Runnable()
{
@Override
public void run()
{
long averageTime = 0;
for (int i = 0; i < 10; i++)
{
File file = new File(getFilesDir(), String.valueOf(i) + ".file");
FileOutputStream fileOutputStream = null;
try
{
fileOutputStream = new FileOutputStream(file);
}
catch (FileNotFoundException e)
{
Log.e(TAG, "", e);
return;
} long startTime = System.currentTimeMillis();
testHttpClient(fileOutputStream);
long stopTime = System.currentTimeMillis(); averageTime += stopTime - startTime;
}
averageTime /= 10; // 测试完成
Message msg = new Message();
msg.what = MSG_TEST_HTTP_CLIENT_DONE;
msg.obj = averageTime;
mHandler.sendMessage(msg);
}
}).start(); return;
} if (v.equals(mTestHttpUrlConnectionBtn))
{
new Thread(new Runnable()
{
@Override
public void run()
{
long averageTime = 0;
for (int i = 0; i < 10; i++)
{
File file = new File(getFilesDir(), String.valueOf(i + 10) + ".file");
FileOutputStream fileOutputStream = null;
try
{
fileOutputStream = new FileOutputStream(file);
}
catch (FileNotFoundException e)
{
Log.e(TAG, "", e);
return;
} long startTime = System.currentTimeMillis();
testHttpUrlConnection(fileOutputStream);
long stopTime = System.currentTimeMillis(); averageTime += stopTime - startTime;
}
averageTime /= 10; // 测试完成
Message msg = new Message();
msg.what = MSG_TEST_HTTP_URL_CONNECTION_DONE;
msg.obj = averageTime;
mHandler.sendMessage(msg);
}
}).start(); return;
}
} private void testHttpClient(FileOutputStream fileOutputStream)
{
DefaultHttpClient httpClient = new DefaultHttpClient(); HttpEntity entity = null;
InputStream inputStream = null;
try
{
HttpGet httpGet = new HttpGet(TEST_URL);
HttpResponse httpResponse = httpClient.execute(httpGet); StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine == null)
{
throw new Exception("no status line !!!");
}
int responseCode = statusLine.getStatusCode();
if (responseCode < 200 || responseCode >= 300)
{
throw new Exception("response error !!!");
}
entity = httpResponse.getEntity();
if (entity == null)
{
throw new Exception("no entity !!!");
}
inputStream = entity.getContent();
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1)
{
fileOutputStream.write(buffer, 0, bytesRead);
}
}
catch (Exception e)
{
Log.e(TAG, "", e);
}
finally
{
try
{
if (inputStream != null)
{
inputStream.close();
} if (entity != null)
{
entity.consumeContent();
} if (fileOutputStream != null)
{
fileOutputStream.flush();
fileOutputStream.close();
}
}
catch (Exception e)
{
Log.e(TAG, "", e);
}
}
} private void testHttpUrlConnection(FileOutputStream fileOutputStream)
{
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try
{
httpURLConnection = (HttpURLConnection) new URL(TEST_URL).openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect(); int responseCode = httpURLConnection.getResponseCode();
if (responseCode < 200 || responseCode >= 300)
{
throw new Exception("response error !!!");
}
inputStream = httpURLConnection.getInputStream();
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1)
{
fileOutputStream.write(buffer, 0, bytesRead);
}
}
catch (Exception e)
{
Log.e(TAG, "", e);
}
finally
{
try
{
if (inputStream != null)
{
inputStream.close();
} if (httpURLConnection != null)
{
httpURLConnection.disconnect();
} if (fileOutputStream != null)
{
fileOutputStream.flush();
fileOutputStream.close();
}
}
catch (Exception e)
{
Log.e(TAG, "", e);
}
}
}

  测试结果如下:

下载文件:360MobileSafe_4.3.5beta.apk 链接:http://msoftdl.360.cn/mobilesafe/shouji360/360safesis/360MobileSafe_4.3.5beta.apk 大小:12.65MB

测试结果: DefaultHttpClient平均耗时:7275ms(第一次) 3861ms(第二次) HttpURLConnection平均耗时:5445ms(第一次) 3119ms(第二次)

HttpURLConnection传输效率更高

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

下载文件:old offender.apk 链接:http://gdown.baidu.com/data/wisegame/79fb2f638cc11043/oldoffender.apk 大小:4.98MB

测试结果: DefaultHttpClient平均耗时:3780ms(第一次) 4008ms(第二次) 4209ms(第三次) HttpURLConnection平均耗时:3718ms(第一次) 4783ms(第二次) 3945ms(第三次)

二者相差无几

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

下载文件:baidu首页html 链接:http://www.baidu.com 大小:使用DefaultHttpClient下载的是11.61KB的html(被baidu视为PC端浏览器访问),使用HttpURLConnection下载的是5.22KB的html(被baidu视为移动端浏览器访问)

测试结果:无效

说明:这也是某些测试说HttpUrlConnection下载速度快几倍所使用的链接,其实根本原因在于这两API下载的html大小就差了两倍,比较结果是不公平的

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

下载文件:baidu首页logo 链接:http://www.baidu.com/img/bdlogo.gif 大小:1.54KB

测试结果:无效

说明:由于文件较小,有时候DefaultHttpClient比HttpURLConnection快很多,而下一秒的测试结果又反过来了,这是因为传输时间相差无几,而连接的耗时不确定,从而导致总耗时相差很大,所以无法判断谁的传输效率更高。

结论:文件越大,可能HttpUrlConnection的速度优势越明显,应该是SDK文档宣称的GZIP压缩传输导致传输时间缩短的原因,当然,前提是服务器得支持GZIP传输~

HttpClient与HttpUrlConnection下载速度比较的更多相关文章

  1. java分别通过httpclient和HttpURLConnection获取图片验证码内容

    前面的文章,介绍了如何通过selenium+Tesseract-OCR来识别图片验证码,如果用接口来访问的话,再用selenium就闲的笨重,下面就介绍一下分别通过httpclient和HttpURL ...

  2. HttpClient和HttpURLConnection的使用和区别(下)

    转自来自点击打开链接 接着上一篇,我们继续来分析HttpURLConnection的使用,以及两者的共同点和区别. 目录 用法 HttpURLConnection 区别 引用资料 用法 HttpURL ...

  3. Android 网络编程之---HttpClient 与 HttpURLConnection 共用cookie

    HttpClient 与 HttpURLConnection 共用 SessionId HttpClient 与 HttpUrlConnection 是Android 中HTTP操作最常见的訪问方式. ...

  4. 为HttpClient和HttpURLConnection添加中国移动代理

    转自: http://www.2cto.com/kf/201111/112100.html 在android中,一般需要联网的时候前,都要做一次网络的判断,判断当前的网络状态!然后开始请求网络 当我们 ...

  5. HttpClient和HttpURLConnection整合汇总对比

    性能 1.HttpUrlConnection直接支持GZIP压缩:HttpClient也支持,但要自己写代码处理. 2.HttpUrlConnection直接支持系统级连接池,即打开的连接不会直接关闭 ...

  6. android 中对apache httpclient及httpurlconnection的选择

    在官方blog中,android工程师谈到了如何去选择apache client和httpurlconnection的问题: 原文见http://android-developers.blogspot ...

  7. Android4种网络连接方式HttpClient、HttpURLConnection、OKHttp和Volley优缺点和性能对比

    比较的指标: 1.cpu 2.流量 3.电量 4.内存占用 5.联网时间 功能点: 1.重试机制 2.提供的扩展功能 3.易用性 4.是否https 5.是否支持reflect api,OkHttp有 ...

  8. HttpClient和HttpURLConnection的使用和区别

    https://www.cnblogs.com/liushuibufu/p/4140913.html 功能用法对比 从功能上对比,HttpURLConnection比HttpClient库要丰富很多, ...

  9. 关于HttpClient,HttpURLConnection,OkHttp的用法

    1 HttpClient入门实例 1.1发送get请求 /** * HttpClient发送get请求 * @param url 请求地址 * @return * @throws IOExceptio ...

随机推荐

  1. 【Beta阶段】第五次Scrum Meeting!

    每日任务内容: 本次会议为第五次Scrum Meeting会议~ 由于本次会议项目经理召开时间依旧较晚,在公寓7层召开,女生参与了线上会议. 队员 昨日完成任务 明日要完成任务 刘乾 #167(未完成 ...

  2. OVS 精确删除流表

    OVS 精确删除流表 前言 今天看了sdnlab小姐姐的mininet教程之后,看到有一个下流表的操作,优先级没能下成功,然后回来实验一下,这个问题是解决了,不过遇到了一个小问题,ovs如何精确删除流 ...

  3. 实现项目WC

    软件的需求分析 程序处理用户需求的模式为: wc.exe [parameter][filename] 在[parameter]中,用户通过输入参数与程序交互,需实现的功能如下: 1.基本功能 支持 - ...

  4. 老李的blog使用日记(3)

    匆匆忙忙.碌碌无为,这是下一个作业,VS,多么神圣高大上,即使这样,有多少人喜欢你就有多少人烦你,依然逃不了被推销的命运,这抑或是它喜欢接受的,但是作为被迫接受者,能做的的也只有接受,而已. 既来之则 ...

  5. [置顶网]POWER 9为云与智能打造强大引擎

    POWER 9为云与智能打造强大引擎 关键字: 浪潮商用机器 POWER9 至顶网服务器频道 (文/董培欣): 从全球角度看,政治经济波动持续.逆全球化趋势抬头.技术加速变革商业等因素促使企业需要数字 ...

  6. RDM 使用与破解

    RDM 的下载地址 https://cdn.devolutions.net/download/Setup.RemoteDesktopManager.13.6.2.0.msi#_ga=2.2471513 ...

  7. delphi制作登陆窗体

    delphi登陆窗体的制作,就我知道的,可以有两种方法,一种是在工程文件中实现登陆窗体的动态调用,另一种就是在主窗体的OnCreate事件中动态创建登陆窗体,两种方法都需要将主窗体设置为Auto-cr ...

  8. mysql 命令行快速将数据库转移到另一个服务器中(数据库备份还原)

    想将A服务器中的数据库快速转移到B服务器中,一般是先从A服务器中备份下来,下载备份数据,还原到B服务器中.使用phpMyAdmin备份和还原针对数据量很小的情况下很方便,数据量大的话很容易中断失败. ...

  9. WebAPI框架里设置异常返回格式统一

    直接上代码 /// <summary> /// 消息代理处理,用来捕获这些特殊的异常信息 /// </summary> public class CustomErrorMess ...

  10. 详细理解servlet实现的三种方式和生命周期

    阅读目录 开发servlet的三种方式 理解实现servlet接口的方式,理解servlet生命周期 Servlet接口有五个方法 继承GenericServlet 继承HttpServlet 现在很 ...