简体   繁体   English

Android 2.3.5和2.3.6上的HttpURLConnection

[英]HttpURLConnection on android 2.3.5 and 2.3.6

After upgrade to android 2.3.5 and 2.3.6, the code for android HttpURLConnection class: urlconn.connect(), urlconn.getOutputStream() and urlconn.getInputStream() becomes very slow (each command takes more than 5 second, under version 2.3.2 or 2.2 it just take less than 1 sec). 升级到android 2.3.5和2.3.6后,android HttpURLConnection类的代码:urlconn.connect(),urlconn.getOutputStream()和urlconn.getInputStream()变得非常慢(每个命令需要5秒以上,版本不足2.3.2或2.2它只需不到1秒)。 Does any one has the same situation? 有没有人有相同的情况?

My codes looks like this: 我的代码如下所示:

getUrl = new URL(url);
urlConn = (HttpURLConnection) getUrl.openConnection();

urlConn.setUseCaches(false);
urlConn.setRequestMethod(httpMethod.name());
urlConn.setConnectTimeout(HTTP_CONNECT_TIMEOUT);
urlConn.setReadTimeout(HTTP_READ_TIMEOUT);
urlConn.setDoInput(true);
if (requestBody != null)
       urlConn.setFixedLengthStreamingMode(requestBody.length());
if (!(httpMethod == HttpMethod.GET))
       urlConn.setDoOutput(true);

urlConn.connect();

if (requestBody != null) {
       osw = new OutputStreamWriter(urlConn.getOutputStream());
       osw.write(requestBody);
       osw.flush();
}

in = urlConn.getInputStream();
buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[256];
while ((nRead = in.read(data, 0, data.length)) != -1) {
       buffer.write(data, 0, nRead);
}
buffer.flush();
responseBody = buffer.toByteArray();
responseCode = urlConn.getResponseCode();

Regards, Zheng 问候,郑

Two bits of advice: 两点建议:

  1. Insert logging statements after each HTTP operation. 在每次HTTP操作后插入日志记录语句。 That way you can see which step is taking the most time. 这样你就可以看出哪一步花费的时间最多。
  2. Reading 256 bytes at a time from the InputStream is going to be rather inefficient. 从InputStream一次读取256个字节将是相当低效的。 In my experience, an 8k buffer size (8192) works best on most devices and networks. 根据我的经验,8k缓冲区大小(8192)在大多数设备和网络上效果最佳。

尝试在单独的线程上运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM