我正在尝试从我的服务器下载文件(mp3)。
我想要显示下载进度,但我面临着文件大小始终为-1的问题。
截图:

我的代码:
try {
URL url = new URL(urls[0]);
// URLConnection connection = url.openConnection();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
int fileSize = connection.getContentLength();
if (fileSize == -1)
fileSize = connection.getHeaderFieldInt("Length", -1);
InputStream is = new BufferedInputStream(url.openStream());
OutputStream os = new FileOutputStream(myFile);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = is.read(data)) != -1) {
total += count;
Log.d("fileSize", "Lenght of file: " + fileSize);
Log.d("total", "Lenght of file: " + total);
// publishProgress((int) (total * 100 / fileSize));
publishProgress("" + (int) ((total * 100) / fileSize));
os.write(data, 0, count);
}
os.flush();
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}我得到了返回-1 (int fileSize = connection.getContentLength();)的fileSize的垃圾值。
发布于 2015-05-10 05:22:31
检查服务器正在发送的报头。很可能服务器发送的是Transfer-Encoding: Chunked,而根本没有Content-Length报头。这是HTTP/1.1中的一种常见做法。如果服务器没有发送长度,客户端显然不知道它。如果是这种情况,并且您无法控制服务器代码,那么最好的做法可能是仅显示微调类型的指示器。
https://stackoverflow.com/questions/30142026
复制相似问题