2011-09-29 713 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 
}