我有一个 Android 应用程序,我想显示下载的天气数据的进度条。我将显示大约 5 个地方的天气预报。问题是当我想从响应头中获取 Content-Length 时。日志总是显示-1(这意味着该字段未在 URLConnection 变量中设置)。
这是我正在使用的代码:
private class DownloadWeatherData extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL("http://www.google.com/ig/api?weather=NY&hl=en&oe=utf-8");
URLConnection connection = url.openConnection();
int dataLenght = connection.getContentLength();
Log.d("ANDRO_ASYNC", "Data lenght: " + dataLenght);
InputStream input = new BufferedInputStream(url.openStream());
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
Log.d("ANDRO_ASYNC", ""+(int)((count)));
}
input.close();
} catch (Exception e) {
}
return null;
}
}
我能做些什么?还是有其他方法可以显示下载数据的进度?