这是您从 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也不同。您需要适应更新版本的手机系统