安卓:"流&QUOT意外结束;除了下载大文件 [英] Android:"Unexpected end of stream" exception downloading large files

查看:153
本文介绍了安卓:"流&QUOT意外结束;除了下载大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建一个Android应用程序,我需要从一个URL,它是33 MB大文件下​​载。

I'm building an Android Application and I need to download a file from a url, which is 33 MB large.

下面的下载任务:

try {
            int MAX_BUFFER_SIZE = 4096;
            URL mUrl = new URL(params[0]);
            HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
            connection.setRequestMethod("GET");
            long length = connection.getContentLength(), downloaded = 0;
            int read;
            byte [] buffer = new byte[(((int)length) > MAX_BUFFER_SIZE) ? MAX_BUFFER_SIZE : (int)length];
            String filename = getFilename(mUrl);
            File file = new File (SDCARD_ROOT);
            if (!file.exists() || !file.isDirectory()){
                file.mkdir();
            }
            this.filename = filename;
            file = new File (SDCARD_ROOT + this.filename);  
            FileOutputStream fos = new FileOutputStream (file);
            //Start downloading
            InputStream stream = connection.getInputStream();

            while ((read=stream.read(buffer)) > -1){
                fos.write(buffer, 0, read);
                downloaded += read;
                publishProgress((int) ((float) downloaded/length * 100));
            }
            fos.close();
            return 1;
        } catch (Exception e){
            Log.e("REV-PARTS", "Revolver parts error in DownloadTask: " + e.getMessage());  
            return 2;
        }

它的工作原理正确处理小文件(1-15 MB),但它会返回一个异常流意外结束大文件。 先谢谢了。

It works right with small files (1-15 mb), but it will return a "unexpected end of stream" exception with large files. Thanks in advance.

推荐答案

这是有关请求方法。默认值是GET。先尝试创建一个HttpURLConnection类,并使用setRequestMethod(POST)。我做了GET方法,并有同样的烦恼,那么我已经改为后,它的工作。这里是code;

It's about request method. The default is "GET". Try creating an HttpURLConnection first, and use setRequestMethod("POST"). I did with GET method and had the same trouble, then I changed to POST and it worked. Here is the code;

 URL url = new URL(urlStr);
 connection = (HttpURLConnection) url.openConnection();
 connection.setRequestMethod("POST");   
 is = connection.getInputStream();

这篇关于安卓:"流&QUOT意外结束;除了下载大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆