2011-09-29 714 views
1

我有一個文件大小5MB &想通過HttpURLConnection下載(目標就像是「http://...../songs/Beatles_And I Love Her.mp3」)。HttpURLConnection讀取輸入流失敗

我想如下

URL url = new URL("http://........../songs/Beatles_And I Love Her.mp3"); 

URLConnection urlConnection = url.openConnection(); 
HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection; 

httpURLConnection.getResponseCode(); 
InputStream stream = httpURLConnection.getInputStream(); 

byte buf[] = new byte[128]; 
do 
{ 
    int numread = stream.read(buf); 
    if (numread <= 0) 
    { 
     stream.close(); 
     break; 
    } 
} while (true); 

做它,但問題是,它只是只讀取2KB數據的3KB和它返回後-1和退出。

+0

你怎麼會知道這只是讀取多少數據? –

+0

嗨,布賴恩,因爲讀了幾個字節後「stream.read(buf);」返回「-1(減一)」,請幫助我。 –

+0

欲瞭解更多信息,每次只從5Mb源讀取「2774」字節。 –

回答

0

試試這個它是爲我工作

try{ 
      if(path != null && fileName != null){ 
       Log.v(TAG, "downloading data"); 

       URL url = new URL(path + fileName); 
       URLConnection conexion = url.openConnection(); 
       conexion.connect(); 

       int lenghtOfFile = conexion.getContentLength(); 
       Log.v(TAG, "lenghtOfFile = "+lenghtOfFile); 

       InputStream is = url.openStream(); 

       File testDirectory = new File(Environment.getDataDirectory().toString() + "/data/" + c.getPackageName() + "/download"); 
       if(!testDirectory.exists()){ 
        testDirectory.mkdir(); 
       } 
       FileOutputStream fos = new FileOutputStream(testDirectory+"/" + fileName); 
       byte data[] = new byte[1024]; 

       int count = 0; 
       long total = 0; 


       while ((count=is.read(data)) != -1) { 
        total += count; 
        int progress_temp = (int)(total * 100)/lenghtOfFile; 
        if((progress_temp % 10) == 0 && (progress != progress_temp)){ 
         progress = progress_temp; 
         Log.v(TAG, "total = "+progress);  
        } 
        fos.write(data, 0, count); 
       } 
       is.close(); 
       fos.close(); 
       Log.v(TAG, "downloading finished"); 
      } 
     }catch(Exception e){ 
      Log.v(TAG, "exception in downloadData"); 
      e.printStackTrace(); 
     } 
+0

這也是,每次僅讀取5Mb源中的「2774」字節。 –

0

增加緩衝區的大小

byte buf[] = new byte[2048]; 
+0

感謝您的迴應,我試過「字節緩衝區[] =新字節[2048];」,但沒有效果 - 這是行不通的。 –

1

檢查響應代碼(應爲200),並檢查你的數據內容。

我有一個類似的問題。原來它是從我讀的服務器,而不是正確的文件中的錯誤頁面:-)

此外,嘗試的文件doesen't包含空格(重命名爲Beatles_And_I_Love_Her.mp3在服務器上)

0

變化

if (numread <= 0) 

if (numread < 0) 

正如the javadoc說你應該只跳出循環的磨片n你得到一個-1:

「讀入緩衝區的字節總數,或-1,如果因爲已到達流的末尾而沒有更多數據。

獲取0個字節的讀取有點奇怪,但可能會發生,因爲數據已被拆分爲底層網絡層的數據包。

1

您有專門用於GOT調用創建從中InputStream之前以下

if(httpURLConnection.getResposecode==HTTPConnection.OK){ 
    // Do your job here 
}else{ 
    //Error in connection creation 
}