httpurlconnection 是轻量级浏览器的吗

HttpURLConnection的connect()步骤作用_读书人
HttpURLConnection的connect()步骤作用
&来源:读书人网&【读书人网():综合教育门户网站】
HttpURLConnection的connect()方法作用如题,我用下面的代码可以实现往服务器端传递数据,URL url new URL
HttpURLConnection的connect()方法作用如题,我用下面的代码可以实现往服务器端传递数据,URL&url&=&new&URL("http://localhost:8088/Test/streamtestserver.do");&&&&&&&&HttpURLConnection&con&=&(HttpURLConnection)url.openConnection();&&&&&&&&con.setRequestMethod("POST");&&&&&&&&&con.setRequestProperty("Content-Type",&"application/stream");&&&&&&&&&&&&&&&&&&con.setDoOutput(true);&&&&&&&&con.setDoInput(true);&&&&&&&&&&&&&&con.setUseCaches(false);&&&&&&&&con.setInstanceFollowRedirects(true);&&&&&&&&con.connect();&&&&&&&&DataOutputStream&d&=&new&DataOutputStream(con.getOutputStream());&&&&&&&&d.write("111".getBytes());&&&&&&&&d.flush();&&&&&&&&d.close();&&&&&&但是我把con.connect();注掉后仍可以实现,所以不知道con.connect();的用处和在,是不是只要&&&&&&url.openConnection();后就已经建立连接了?&&&&&&还有一个问题就是我把d.flush()和d.close()方法去掉后仍可以向服务器端输出数据,那d.flush()的用处是什么?&&&&&&&& [解决办法]API:connectpublic&abstract&void&connect()&&&&&&&&&&&&&&&&&&&&&&throws&IOException打开到此&URL&引用的资源的通信链接(如果尚未建立这样的连接)。&如果在已打开连接(此时&connected&字段的值为&true)的情况下调用&connect&方法,则忽略该调用。&URLConnection&对象经历两个阶段:首先创建对象,然后建立连接。在创建对象之后,建立连接之前,可指定各种选项(例如,doInput&和&UseCaches)。连接后再进行设置就会发生错误。连接后才能进行的操作(例如&getContentLength),如有必要,将隐式执行连接。&抛出:&SocketTimeoutException&-&如果在建立连接之前超时期满&IOException&-&如果打开连接时发生&I/O&错误。另请参见:connected,&getConnectTimeout(),&setConnectTimeout(int)[解决办法]d.flush();//强制把缓冲区的数据写入到文件并清空缓冲区d.close();//关闭连接其实调用close()之前也会强制把缓冲区的数据写入到文件并清空缓冲区,所以一般写一个close就行了,没必要2个都写.close()就是关闭连接,如果不用了就关掉,否则会占用系统资源.  Android有两套http的API,刚开始使用网络编程时多少有些迷惑到底用哪个好呢?其实孰优孰劣无需再争论,google已经指出HttpUrlConnection是Android更优的选择,并在SDK文档中引用了博客(需要代理访问)来阐述各自的优缺点。国内也有些博客大致翻译了上面的内容,并对了一些测试,可惜测试不严密,某博客甚至得出HttpUrlConnection的下载速度快几倍的结论,其实并没有公平反映出二者的下载速度。
  虽然我已经使用过HttpUrlConnection实现了一个轻量级http引擎用于下载,但是好奇心还是促使我写了一个测试程序用于比较二者的性能。由于HttpClient仅仅是一个接口,所以我选用了其实现类DefaultHttpClient和HttpUrlConnection做比较,方法很简单,分别下载同一个文件10次,然后计算耗时的平均值,测试代码片段如下:
public void onClick(View v)
if (v.equals(mTestHttpClientBtn))
new Thread(new Runnable()
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;
fileOutputStream = new FileOutputStream(file);
catch (FileNotFoundException e)
Log.e(TAG, "", e);
long startTime = System.currentTimeMillis();
testHttpClient(fileOutputStream);
long stopTime = System.currentTimeMillis();
averageTime += stopTime - startT
averageTime /= 10;
// 测试完成
Message msg = new Message();
msg.what = MSG_TEST_HTTP_CLIENT_DONE;
msg.obj = averageT
mHandler.sendMessage(msg);
}).start();
if (v.equals(mTestHttpUrlConnectionBtn))
new Thread(new Runnable()
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;
fileOutputStream = new FileOutputStream(file);
catch (FileNotFoundException e)
Log.e(TAG, "", e);
long startTime = System.currentTimeMillis();
testHttpUrlConnection(fileOutputStream);
long stopTime = System.currentTimeMillis();
averageTime += stopTime - startT
averageTime /= 10;
// 测试完成
Message msg = new Message();
msg.what = MSG_TEST_HTTP_URL_CONNECTION_DONE;
msg.obj = averageT
mHandler.sendMessage(msg);
}).start();
private void testHttpClient(FileOutputStream fileOutputStream)
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity entity = null;
InputStream inputStream = null;
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);
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;
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);
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 链接: 大小:12.65MB
测试结果: DefaultHttpClient平均耗时:7275ms(第一次) 3861ms(第二次) HttpURLConnection平均耗时:5445ms(第一次) 3119ms(第二次)
HttpURLConnection传输效率更高
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
下载文件:old offender.apk 链接: 大小:4.98MB
测试结果: DefaultHttpClient平均耗时:3780ms(第一次) 4008ms(第二次) 4209ms(第三次) HttpURLConnection平均耗时:3718ms(第一次) 4783ms(第二次) 3945ms(第三次)
二者相差无几
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
下载文件:baidu首页html 链接: 大小:使用DefaultHttpClient下载的是11.61KB的html(被baidu视为PC端浏览器访问),使用HttpURLConnection下载的是5.22KB的html(被baidu视为移动端浏览器访问)
测试结果:无效
说明:这也是某些测试说HttpUrlConnection下载速度快几倍所使用的链接,其实根本原因在于这两API下载的html大小就差了两倍,比较结果是不公平的
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
下载文件:baidu首页logo 链接: 大小:1.54KB
测试结果:无效
说明:由于文件较小,有时候DefaultHttpClient比HttpURLConnection快很多,而下一秒的测试结果又反过来了,这是因为传输时间相差无几,而连接的耗时不确定,从而导致总耗时相差很大,所以无法判断谁的传输效率更高。
结论:文件越大,可能HttpUrlConnection的速度优势越明显,应该是SDK文档宣称的GZIP压缩传输导致传输时间缩短的原因,当然,前提是服务器得支持GZIP传输~
阅读(...) 评论()HttpURLConnection和HttpClient
我的图书馆
HttpURLConnection和HttpClient
1&&private&void&disableConnectionReuseIfNecessary()&{
2&&&&&//&HTTP&connection&reuse&which&was&buggy&pre-froyo
3&&&&&if&(Integer.parseInt(Build.VERSION.SDK)&&&Build.VERSION_CODES.FROYO)&{
4&&&&&&&&&System.setProperty("http.keepAlive",&"false");
&1&private&void&enableHttpResponseCache()&{
&2&&&&&try&{
&3&&&&&&&&&long&httpCacheSize&=&10&*&1024&*&1024;&//&10&MiB
&4&&&&&&&&&File&httpCacheDir&=&new&File(getCacheDir(),&"http");
&5&&&&&&&&&Class.forName("android.net.http.HttpResponseCache")
&6&&&&&&&&&&&&&.getMethod("install",&File.class,&long.class)
&7&&&&&&&&&&&&&.invoke(null,&httpCacheDir,&httpCacheSize);
&8&&&&&}&catch&(Exception&httpResponseCacheNotAvailable)&{
TA的最新馆藏

我要回帖

更多关于 轻量级linux 的文章

 

随机推荐