2015-06-11 178 views
0

我正在嘗試創建可下載音樂文件的應用程序。從url下載mp3文件

如何從Android下載mp3文件並將其保存在SD卡中?

我用這個代碼,但始終lenghtOfFile<=350

String fileUrl = (String) params[0]; 
       path = (String) params[1]; 
       InputStream input = null; 
       OutputStream output = null; 
       HttpURLConnection connection = null; 
       int count; 
       try { 
        URL url = new URL(fileUrl); 
        URLConnection connection = url.openConnection(); 
        connection .connect(); 
        // this will be useful so that you can show a tipical 0-100% progress bar 
        int lenghtOfFile = connection .getContentLength(); 

        // downlod the file 
        input = new BufferedInputStream(url.openStream()); 
        output = new FileOutputStream(path); 

        byte data[] = new byte[1024]; 

        long total = 0; 

        while ((count = input.read(data)) != -1) { 
         total += count; 
         // publishing the progress.... 
         publishProgress((int)(total*100/lenghtOfFile)); 
         output.write(data, 0, count); 
        } 

        output.flush(); 
        output.close(); 
        input.close(); 

URL文件:

http://snd1.tebyan.net/1391/12/08_Khaneh_D_117323.mp3 
http://snd1.tebyan.net/1393/12/100_Pedar_Va_Madar_D_148797.mp3 
and ..... 

更新:

int code= connection.getResponseCode();\\302 
String _result= connection.getResponseMessage();\\ found 

注:

文件都下載Samsung Galaxy S3,但文件不會在Samsung tablet N8000

+1

我會看看實際的響應 - 你確定你的狀態是200(連接工作和URL被發現)? –

+0

你的網址無法使用! –

+0

connection.getResponseCode = 302 and connection.getResponseMessage =「found」 – testStack

回答

0

下載您可以實現HMTL5並從那裏做,可能需要一些JS ...

+0

請給我一個例子 – testStack

0

爲302響應,你需要connection.setInstanceFollowRedirects(true)到跟着它。之前connection.connect()

+0

沒有爲我工作 – testStack

+0

'String newUrl = conn.getHeaderField(「Location」);'再次請求這個新的url。 –