2011-11-29 166 views
2

我已經開發了應用程序,其中我需要從url下載文件,我試過下面的代碼,但是當我顯示細節時,我得到了0字節。問題在下載文件

代碼::

package com.playmusic; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import android.app.Activity; 
import android.os.Bundle; 
import android.os.Environment; 
import android.util.Log; 


public class playmusic extends Activity { 

private static String fileName = "shanesh.mp3"; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    try { 
     URL url = new URL("URl"); 
     HttpURLConnection c = (HttpURLConnection) url.openConnection(); 
     c.setRequestMethod("GET"); 
     c.setDoOutput(true); 
     c.connect(); 

     String PATH = Environment.getExternalStorageDirectory() 
       + "/download/"; 
     Log.v("log_tag", "PATH: " + PATH); 
     File file = new File(PATH); 
     file.mkdirs(); 
     File outputFile = new File(file, fileName); 
     FileOutputStream fos = new FileOutputStream(outputFile); 

     InputStream is = c.getInputStream(); 

     byte[] buffer = new byte[1024]; 
     int len1 = 0; 
     while ((len1 = is.read(buffer)) != -1) { 
      fos.write(buffer, 0, len1); 
     } 
     fos.close(); 
     is.close(); 
    } catch (IOException e) { 
     Log.d("log_tag", "Error: " + e); 
    } 
    Log.v("log_tag", "Check: "); 
} } 

清單:

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> 
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> 
+0

什麼是URL url = new URL( 「URL」); ?????????你指定http url嗎? –

+0

雅我指定http在我的網址 –

+0

然後告訴我你在哪裏得到異常??????? –

回答

0

做如下。

HttpClient httpclient = new DefaultHttpClient(); 

    HttpGet httpget = new HttpGet("http://www.mysite.com/file.txt"); 



    try { 

     // Execute HTTP Get Request 

     HttpResponse response = httpclient.execute(httpget); 

     HttpEntity entity = response.getEntity(); 



     printAsString(entity.getContent())); 



    } catch (IOException e) { 

     Log.e(TAG, "There was an IO Stream related error", e); 

    } 





private void printAsString(InputStream is) { 

    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 

    StringBuilder builder = new StringBuilder(); 

    String line; 



    try { 

     while ((line = reader.readLine()) != null) { 

      Syso(line); 

     } 

    } catch (IOException e) { 

     Log.d(TAG, "Error while converting input stream to string"); 

    } 

    is.close(); 

} 
+1

你能告訴,你想要2知道嗎?..我真的不明白你期待..你期待所有答案闡述..嘗試以上n如果您遇到任何問題,請發帖。 – Jayabal

+0

我在下載mp3文件中獲得成功,但沒有在mp4中獲得成功 –

0

這是我用它來下載一個文件的代碼。試試這個

DefaultHttpClient http = new DefaultHttpClient(); 
HttpGet method = new HttpGet(YOUR URL); 
HttpResponse res = http.execute(method); 
InputStream responseStream = res.getEntity().getContent(); 

這裏我使用GET方法並將參數追加到URL中。

+0

可以給你更詳細的說明 –

+0

你能告訴我什麼是區別我的方法和你的方法? –

+0

我已經使用'URL url = new URL(「url」); HttpURLConnection c =(HttpURLConnection)url.openConnection(); c.setRequestMethod(「GET」); c.setDoOutput(true); c.connect();' –

0

試試這個:

 int count; 

    try { 
      URL url = new URL("URl"); 
      HttpURLConnection c = (HttpURLConnection) url.openConnection(); 
      c.setRequestMethod("GET"); 
      c.setDoOutput(true); 
      c.connect(); 



      String PATH = Environment.getExternalStorageDirectory() 
        + "/altered/"; 
      Log.v("log_tag", "PATH: " + PATH); 
      File file = new File(PATH); 
       if (!file.exists()) { 
       file.mkdirs(); 
       } 
      File outputFile = new File(file,name); 
      FileOutputStream fos = new FileOutputStream(outputFile); 


      // getting file length 
      int lenghtOfFile = c.getContentLength(); 

      InputStream is = c.getInputStream(); 

      byte buffer[] = new byte[1024]; 

      long total = 0; 

      while ((count = is.read(buffer)) != -1) { 

       total += count; 

       // publishing the progress.... 
       // After this onProgressUpdate will be called 
       publishProgress("" + (int) ((total * 100)/lenghtOfFile)); 

       fos.write(buffer); 

      } 
      fos.close(); 
      is.close(); 
     } catch (IOException e) { 
      Log.e("log_tag", "Error: " + e); 
     } 
1

這是簡單的代碼來下載喜歡的圖像,音頻的任何文件,視頻等

Button start; 
    //String HttpMyUrl="http://am.cdnmob.org/_/img/loader-small.gif"; 
    String HttpMyUrl="http://ringtones.mob.org/ringtone/RIusrm-7xATkRQlLw1o89w/1424909358/fa1b23bb5e35c8aed96b1a5aba43df3d/stefano_gambarelli_feat_pochill-land_on_mars_v2.mp3"; 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     start= (Button) findViewById(R.id.startBtn); 
     start.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       DownloadManager.Request request = new DownloadManager.Request(Uri.parse(HttpMyUrl)); 
       request.setTitle("File Download"); 
       request.setDescription("File is being Downloaded..."); 
       request.allowScanningByMediaScanner(); 
       request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
       String fileName = URLUtil.guessFileName(HttpMyUrl,null, MimeTypeMap.getFileExtensionFromUrl(HttpMyUrl)); 
       request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName); 
       DownloadManager manager =(DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE); 
       manager.enqueue(request); 
      } 


     }); 

給你許可