尝试从带有空格的URL下载PDF时的FileNotFoundExecption

时间:2014-11-06 16:51:15

标签: android url

我尝试使用以下代码下载,然后最终查看PDF文件。该文件的URL如下所示:

http://www.example.com/directory/something.example.com This File.pdf

我已尝试用%20替换空格,我已经尝试过" UrlEncoder.encode",无论我得到FileNotFoundException还是MalformedURLException(编码URL时)。示例例外:

java.io.FileNotFoundException: http://www.example.com/directory/something.example.com This File.pdf

java.io.FileNotFoundException: http://www.example.com/directory/something.example.com%20This%20File.pdf

java.net.MalformedURLException: Protocol not found: http%3A%2F%2Fwww.example.com%directory%2Fsomething.example.com+This+File.pdf

如果我将这些路径复制到任何浏览器,它会下载得很好。

        File file;
        try
        {
            String urlString = 
              "http://www.example.com/directory/something.example.com This File.pdf"
            URL url = new URL(urlString);
            //URL url = new URL(URLEncoder.encode(urlString, "UTF-8"));
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.connect();

            file = new File(getExternalFilesDir(null), "test.pdf");
            FileOutputStream fileOutput = new FileOutputStream(file);
            InputStream inputStream = urlConnection.getInputStream();

            byte[] buffer = new byte[1024 * 1024];
            int bufferLength;
            while ((bufferLength = inputStream.read(buffer)) > 0)
            {
                fileOutput.write(buffer, 0, bufferLength);
            }

            fileOutput.flush();
            fileOutput.close();
            inputStream.close();
            return file.getAbsolutePath();
        }
        catch (Exception e)
        {
            Log.e(getClass().getSimpleName(), e.getMessage(), e);
            return "";
        }

2 个答案:

答案 0 :(得分:0)

如果服务器以 404 错误代码响应,则会返回例外java.io.FileNotFoundException。有时错误代码和返回的数据不匹配。您可以使用以下命令检查(并获取返回的任何数据):

boolean isError = urlConnection.getResponseCode() >= 400;
InputStream inputStream =  = isError ? urlConnection.getErrorStream() : urlConnection.getInputStream();

如果您要连接到非标准端口,可以通过在请求中添加这些标头来修复它:

urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
urlConnection.setRequestProperty("Accept","*/*");

答案 1 :(得分:0)

您的UrlEncoder尝试错误。这是javadoc: http://docs.oracle.com/javase/6/docs/api/java/net/URLEncoder.html

java.io.FileNotFoundException: http://www.example.com/directory/something.example.com此File.pdf 空格未编码,因此与您的文件不匹配。

java.io.FileNotFoundException: http://www.example.com/directory/something.example.com%20This%20File.pdf %20是有效的网址符号,因此这也与您的文件不符。

java.net.MalformedURLException:找不到协议: HTTP%3A%2F%2Fwww.example.com%目录%2Fsomething.example.com +这+ File.pdf .com之后的斜线编码不正确。导致编码错误的网址。

  1. 使用UrlEncoder,您应该对文件名进行编码并将其与URL连接,而不是对整个url字符串进行编码并使用UTF-8编码。其他任何东西(不是UTF-8)都不能保证有效。
  2. 如果没有手动编码空格,则将它们传递给UrlEncoder。