2012-11-13 159 views
3

我目前的Android應用程序下載了一些音頻文件。當我使用這個代碼來執行下載我收到文件未發現異常:android應用程序下載文件

try { 

    final URL downloadFileUrl = new URL("http://filelocation/url.m4a"); 
    final HttpURLConnection httpURLConnection = (HttpURLConnection) downloadFileUrl.openConnection(); 
    httpURLConnection.setRequestMethod("GET"); 
    httpURLConnection.setDoOutput(true); 
    httpURLConnection.setConnectTimeout(10000); 
    httpURLConnection.setReadTimeout(10000); 
    httpURLConnection.connect(); 

    mTrackDownloadFile = new File(Record.this.getCacheDir(), "mediafile"); 
    mTrackDownloadFile.createNewFile(); 
    final FileOutputStream fileOutputStream = new FileOutputStream(mTrackDownloadFile); 
    final byte buffer[] = new byte[16 * 1024]; 

    final InputStream inputStream = httpURLConnection.getInputStream(); 

    int len1 = 0; 
    while ((len1 = inputStream.read(buffer)) > 0) { 
     fileOutputStream.write(buffer, 0, len1); 
    } 
    fileOutputStream.flush(); 
    fileOutputStream.close(); 

} catch (final Exception exception) { 
    Log.i(TAG, "doInBackground - exception" + exception.getMessage()); 
    exception.printStackTrace(); 
    mTrackDownloadFile = null; 
} 

當我使用這個代碼,它工作正常:

try { 

    final URL downloadFileUrl = new URL("http://filelocation/url.m4a"); 
    final URLConnection urlConnection = downloadFileUrl.openConnection(); 

    mTrackDownloadFile = new File(PlayOpponent.this.getCacheDir(), "mediafile"); 
    mTrackDownloadFile.createNewFile(); 
    final FileOutputStream fileOutputStream = new FileOutputStream(mTrackDownloadFile); 
    final byte buffer[] = new byte[16 * 1024]; 

    final InputStream inputStream = urlConnection.getInputStream(); 

    int len1 = 0; 
    while ((len1 = inputStream.read(buffer)) > 0) { 
     fileOutputStream.write(buffer, 0, len1); 
    } 
    fileOutputStream.flush(); 
    fileOutputStream.close(); 
} catch (final Exception exception) { 
    Log.i(TAG, "doInBackground - exception" + exception.getMessage()); 
    exception.printStackTrace(); 
    mTrackDownloadFile = null; 
} 

可有人請指出我要去的地方錯了嗎?

回答

4

根據這一blog在你的代碼可能會解決問題消除

httpURLConnection.setDoOutput(true); 

。據說這是一個ICS問題。

+0

不錯的一個,我會給你一個嘗試並回復你 – Hector

+0

這篇博客文章描述了這個問題:http://webdiary.com/2011/12/14/ics-get-post/ – petrnohejl

相關問題