其他分享
首页 > 其他分享> > android应用下载文件

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;
}

有人可以指出我要去哪里了吗?

解决方法:

根据这个blog去除

httpURLConnection.setDoOutput(true);

在您的代码中可以解决问题.据说这是ICS问题.

标签:httpurlconnection,urlconnection,android
来源: https://codeday.me/bug/20191031/1977376.html