微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

这是您从 HTTP 下载文件的方式吗?

如何解决这是您从 HTTP 下载文件的方式吗?

在网上阅读教程后,我想出了这个从 HTTP 下载声音文件功能

        try {
            URL url = new URL(filePath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.connect();

            File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File directory = new File(storage.getAbsolutePath());
            directory.mkdirs();

            file = new File(directory,fileName + ".mp3");

            FileOutputStream fileOutput = new FileOutputStream(file);

            InputStream inputStream = urlConnection.getInputStream();

             totalSize = urlConnection.getContentLength();
            int downloadedSize = 0;
            byte[] buffer = new byte[1024];
            int bufferLength = 0; //used to store a temporary size of the buffer


            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutput.write(buffer,bufferLength);
                downloadedSize += bufferLength;
                Log.i("download:",downloadedSize + "/" + totalSize);
            }

            fileOutput.close();
        } catch (IOException e) {
            e.printstacktrace(); 
        }

它在我的设备和所有类型的模拟器上运行良好,但有些用户抱怨无法下载文件。 有什么我想念的吗?为什么它可以在我的设备上运行,但在其他一些设备上却失败了? 如果有人可以查看它并告诉我这是否正确完成,我会很高兴。

解决方法

urlConnection.setDoOutput(true);

不正确。您没有向服务器发送内容。

,

我觉得是因为其他人手机系统版本不同,API也不同。您需要适应更新版本的手机系统

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。