Android版本> 2.3上的FileNotFoundException

Lea*_*ros 13 java android inputstream filenotfoundexception

我尝试在手机上将文件下载到SD卡.在Android 2.1,2.2和2.3上,一切都像预期的那样,但在Android 4.0(在模拟器和我的Galaxy Nexus上测试)它会抛出一个FileNotFoundException.

堆栈跟踪:

02-27 21:49:06.733: W/System.err(27648): java.io.FileNotFoundException: http://www.wdr.de/wdrlive/media/wdr5.m3u
02-27 21:49:06.733: W/System.err(27648):    at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
02-27 21:49:06.733: W/System.err(27648):    at de.arvidg.test.StartActivity$9.run(StartActivity.java:833)
02-27 21:49:06.733: W/System.err(27648):    at java.lang.Thread.run(Thread.java:856)
Run Code Online (Sandbox Code Playgroud)


我下载文件的方法:

downloadFile("http://www.wdr.de/wdrlive/media/wdr5.m3u");

    public void downloadFile(final String fileUrl) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {

                    URL url = new URL(fileUrl);

                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                    urlConnection.setRequestMethod("GET");
                    urlConnection.setDoOutput(true);

                    urlConnection.connect();

//                  File cacheDir = appContext.getExternalCacheDir();
//                  File file = new File("/mnt/sdcard", "/cacheFile.ext");
                    File SDCardRoot = Environment.getExternalStorageDirectory();
                    File file = new File(SDCardRoot,"/cacheFile.ext");

                    if(!file.exists()) file.createNewFile();

                    FileOutputStream fileOutput = new FileOutputStream(file);

                    InputStream inputStream = urlConnection.getInputStream();

                    int totalSize = urlConnection.getContentLength();
                    int downloadedSize = 0;

                    byte[] buffer = new byte[1024];
                    int bufferLength = 0;

                    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                        fileOutput.write(buffer, 0, bufferLength);
                        downloadedSize += bufferLength;
                        Log.d(TAG, "downloadedSize = " + downloadedSize + " | totalSize = " + totalSize);
//                      updateProgress(downloadedSize, totalSize);

                    }
                    fileOutput.close();

            } catch (MalformedURLException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }
Run Code Online (Sandbox Code Playgroud)

Lea*_*ros 37

简单删除 urlConnection.setDoOutput(true);

感谢pfn @#android-dev

  • 显然,JAVA中的这一行强制http协议将GET更改为POST,而不管指定GET (5认同)

Ste*_*nca 8

因此,要回答原始问题,FileNotFoundException当您从服务器收到错误消息然后尝试访问时,也会出现问题getInputStream().如果响应代码是400或更高,任何调用都getInputStream()将抛出此错误.在这种情况下,您应该检查getErrorStream().在这里看到我的答案.