Android url.openStream慢吗?
Im使用以下代码从http服务器检索一些文本。大小小于1 kB,并在0.002毫秒内生成 然而,检索数据可能需要600毫秒,但大多在2000到5000毫秒之间 使用以下代码:Android url.openStream慢吗?,android,Android,Im使用以下代码从http服务器检索一些文本。大小小于1 kB,并在0.002毫秒内生成 然而,检索数据可能需要600毫秒,但大多在2000到5000毫秒之间 使用以下代码: long starttime = System.currentTimeMillis(); StringBuffer SB = new StringBuffer(); Common.toLog("101 took "+ (System.currentTimeMillis() - starttime)
long starttime = System.currentTimeMillis();
StringBuffer SB = new StringBuffer();
Common.toLog("101 took "+ (System.currentTimeMillis() - starttime) + " ms");
try {
URL url = new URL(Common.server+request);
Common.toLog("102 took "+ (System.currentTimeMillis() - starttime) + " ms");
InputStreamReader ISR = new InputStreamReader(url.openStream());
Common.toLog("102a took "+ (System.currentTimeMillis() - starttime) + " ms");
BufferedReader in = new BufferedReader(ISR);
Common.toLog("103 took "+ (System.currentTimeMillis() - starttime) + " ms");
String inputLine;
while ((inputLine = in.readLine()) != null) {
SB.append(inputLine);
}
in.close();
Common.toLog("105 took "+ (System.currentTimeMillis() - starttime) + " ms");
} catch (IOException e)
{
Common.toLog("Could not make connection 1");
showMSG(R.string.ERROR_NO_INTERNET, true);
}
最耗时的方法是在日志点102和点102a之间。使用chrome时,我可以在300-350毫秒内加载。我想知道是否有更有效的方法来检索此数据您要提取的数据实际上并不长。尝试使用HttpRequest的实现之一,而不是打开URL的读取流: 这样,只需发出一个请求,您的数据就会在响应中返回。例如,您可以尝试HttpGet请求:
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
使用以下脚本比以前更好:但是:第一个请求的响应时间仍然需要1600毫秒,而下一个请求的响应时间为+/-700秒