简体   繁体   中英

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). 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. 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. In my experience, an 8k buffer size (8192) works best on most devices and networks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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