6
我試圖從我的服務器上下載文件(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
垃圾值
使用像**'curl' **這樣的命令行工具檢查手動下載此URL時從服務器返回的標頭。也許服務器沒有設置任何與長度相關的頭文件。 – CommonsWare
有時長度未知 - 它取決於服務器端。您的解決方案沒有錯 – Toumash
@Prosanto正如我所見,即使它沒有正確顯示它應該下載。下載的文件是否工作? – Chaoz