我正在下载一个网页,然后使用正则表达式提取一些数据,使用正则表达式(不要大叫我,我知道一个合适的解析器会更好,但这是一个非常简单的机器生成的页面)。这在模拟器中正常工作,在使用wi-fi连接时在我的手机上工作良好,但在3G上不起作用 - 返回的字符串不一样,我也没有匹配。我可以想象它与数据包大小或延迟有关,但我无法弄清楚。使用Android下载网页
我的代码:
public static String getPage(URL url) throws IOException {
final URLConnection connection = url.openConnection();
HttpGet httpRequest = null;
try {
httpRequest = new HttpGet(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream stream = bufHttpEntity.getContent();
String ct = connection.getContentType();
final BufferedReader reader;
if (ct.indexOf("charset=") != -1) {
ct = ct.substring(ct.indexOf("charset=") + 8);
reader = new BufferedReader(new InputStreamReader(stream, ct));
}else {
reader = new BufferedReader(new InputStreamReader(stream));
}
final StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
stream.close();
return sb.toString();
}
这是我造成这种连接不良,或者是有一个错误在那里?无论哪种方式,我该如何解决它?
更新: 下载超过3G的文件是一个比通过Wi-Fi更小的201个字节。虽然他们显然都在下载正确的页面,但3G却缺少一大堆空白,还有一些HTML注释出现在原始页面中,我觉得有点奇怪。 3G在3G上采用不同的页面来减少文件大小?
您是否尝试过比较通过3G下载的内容与以其他方式下载的内容?他们有什么不同? – pkaeding 2010-07-01 14:12:22
经过许多麻烦,我设法从设备上获取文件 - 查看更新后的问题。 – blork 2010-07-01 14:37:28
无关的问题,你在这里不必要地解雇两个请求。一个使用'URL#openConnection()',另一个使用'HttpClient#execute()'。摆脱'URL#openConnection()'行并继续使用'HttpClient'。 'HttpResponse'类有一个'getHeaders()'方法。使用它来获取“Content-Type”标题。 – BalusC 2010-07-01 14:43:51