我想从我的服务器下载文件(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();
}
Run Code Online (Sandbox Code Playgroud)
我得到了fileSize返回-1(int fileSize = connection.getContentLength();)的垃圾值
检查服务器发送的标头。很可能服务器正在发送Transfer-Encoding: Chunked但Content-Length根本没有标头。这是 HTTP/1.1 中的常见做法。如果服务器不发送长度,客户端显然无法知道。如果是这种情况,并且您无法控制服务器代码,最好的办法可能是仅显示微调类型的指示器。