2015-05-09 58 views
6

我試圖從我的服務器上下載文件(mp3)。文件下載 - 負文件長度

我想顯示下載進度,但我面臨的問題是整個文件的大小是-1

的截圖: enter image description here
我的代碼:

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(); 
    } 

我得到它返回-1int fileSize = connection.getContentLength();)的fileSize垃圾值

+0

使用像**'curl' **這樣的命令行工具檢查手動下載此URL時從服務器返回的標頭。也許服務器沒有設置任何與長度相關的頭文件。 – CommonsWare

+2

有時長度未知 - 它取決於服務器端。您的解決方案沒有錯 – Toumash

+0

@Prosanto正如我所見,即使它沒有正確顯示它應該下載。下載的文件是否工作? – Chaoz

回答

2

檢查服務器發送的報頭。很可能服務器發送Transfer-Encoding: Chunked並且沒有Content-Length標題。這是HTTP/1.1中的常見做法。如果服務器沒有發送長度,客戶顯然不知道它。如果是這種情況,並且您無法控制服務器代碼,則最好的做法可能只是顯示一個微調器類型的指示器。