2011-11-29 3 views
2

내가 url에서 파일을 다운로드해야하고 내가 다음과 같은 코드를 시도했지만 내가 세부 보여줄 때 0 바이트있어 applicatin을 개발했습니다.문제가 다운로드 파일

코드 :

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 ("UR1"); ????????? http url을 지정 하시겠습니까 ?? –

+0

나중에 내 URL에 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 명이 알기를 원할 때 와트는 말할 수 있습니까? .. 정말로 나는 기대하는 와트를 이해할 수 없습니다 .. 모든 대답에 대해 자세히 예상하고 있습니다. u가 어떤 prob와 마주 치면 게시하십시오. – Jayabal

+0

나는 mp3 파일을 다운로드해도 성공하지만 mp4에서는 성공하지 못한다. –

0

이 내가 파일을 다운로드하는 데 사용하는 코드입니다. 시도해보십시오.

여기서는 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); 
      } 


     }); 

권한