android - 下载文件时出现 InputStream 异常

标签 android download inputstream

我正在尝试从服务器下载 PPT 文件。 它以字节为单位。

但在调试时我注意到输入流在运行时抛出 FileNotFound 异常。该文件确实存在于服务器上,这是我的代码,我们将不胜感激。

public class DownloadFileAsync extends AsyncTask<String, String, String> {


@Override
protected String doInBackground(String... aurl) {
    int count;

    try {
        URL url = new URL(aurl[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.addRequestProperty("Authorization", "Basic " + SharedPref.getAuthPrefValue());
        connection.addRequestProperty("Device", BaseApplication.getCurrentDevice().getDevice().toString());
        connection.addRequestProperty("DeviceId", BaseApplication.getCurrentDevice().getDeviceId());
        connection.connect();

        int lengthOfFile = connection.getContentLength();
        Log.d("ANDRO_ASYNC", "Length of file: " + lengthOfFile);

        InputStream input = new BufferedInputStream(url.openStream());
        File sdcardDest = new File(Environment.getExternalStorageDirectory(), "Availo");
        String finalDest = sdcardDest + File.separator + "Check1" + "." + "PPT";
        OutputStream output = new FileOutputStream(finalDest);

        byte data[] = new byte[1024];

        long total = 0;

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

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

    } catch (Exception e) {
        e.printStackTrace();
    }


    return null;
}

我在 Mac 上使用 Charles(类似于 Windows 上的 fiddler)来查看我从服务器发送和接收的内容, 服务器没有返回任何错误,尽管它显示了 6-7 秒的下载步骤,下载了大约 400 字节然后停止。

异常从输入流中抛出。

谢谢!

最佳答案

我建议你看看 DownloadManager系统服务。它专为您要执行的操作而设计:

(来自文档)

The download manager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots

关于android - 下载文件时出现 InputStream 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28197834/

相关文章:

Android:从互联网下载文件时互联网关闭时如何处理?

android - Google Play 服务无效

android - 在 Nexus (7.1.1) 上获取导航栏方向(左/右)

java - Gradle 无法下载 okhttp.jar (com.squareup.okhttp3 :okhttp:3. 8.0)

css - Firefox 和 Safari 不会仅从我的服务器下载文件

c++ - 如何将 'fixed' floatfield 用于 istream/istringstream?

java - 使用 libGDX 在 Java 中创建对话

javascript - javascript下载功能的单元测试

asp.net - IE7 在重定向到大型 Excel 文件时出现问题

java - 如何将 InputStream 转换为 InputSource?