我正在使用以下愚蠢的代码下载一些数据:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
request.setHeader("User-Agent","Android Browser");
HttpResponse response = client.execute(request);
in=response.getEntity().getContent();
len=(int)response.getEntity().getContentLength();
if (len<=0) return null;
data=new byte[len];
...以这种方式下载数据非常慢,而且经常会因为连接超时而失败。同样的情况也发生在其他用户的设备上,所以我的网络配置不应该是原因。
另一方面,当我在普通浏览器中输入给定的"url“时,它工作得很好,速度很快,几乎可以立即返回结果。我的Android设备和装有该浏览器的“普通”电脑运行在同一个WLAN网络上。那么这里可能出了什么问题呢?
发布于 2012-05-17 23:53:17
很可能你在引用的代码之外做了一些有趣的事情,你可以运行这个函数并在日志中查看完成请求需要多长时间吗?
function check_fetch_time(String url) {
long start = System.currentTimeMillis();
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
try {
flushContent( response.getEntity().getContent() );
} catch (Exception e) {}
long elapsed = System.currentTimeMillis() - start;
Log.v(TAG, "page fetched in " + elapsed + "ms");
}20秒。是的,真的是秒,不是毫秒。
好吧,这里肯定有些不对劲。您可以打开手机上的浏览器并尝试访问web吗?如果浏览器访问同样慢,这不是你的软件的问题,也许你的邻居正在用微波炉加热他们的香肠,扰乱了你的wifi。然而,如果浏览器几乎立即打开页面(在一两秒内),那么您的程序中就有一些有趣的东西。在这种情况下,我会创建空的HelloWorld项目,将check_fetch_time()复制到那里,然后重试。
发布于 2012-05-17 23:26:18
对我来说,在模拟器中运行应用程序(慢)和在手机中运行应用程序(快)之间有很大的不同。超时可能是因为The服务器在一段时间后关闭了连接。但也尝试使用缓冲读取器。
private static JSONArray getJSON(String url) {
// initialize
InputStream is = null;
JSONArray res = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
res = new JSONArray(sb.toString());
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return res;
}https://stackoverflow.com/questions/10638608
复制相似问题