我試圖使用下面的代碼來下載並最終查看PDF文件。該文件的URL是這樣的:嘗試從空格的URL下載PDF時FileNotFoundExecption
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 "";
}
你用'+'替換了空格嗎? – laalto 2014-11-06 16:58:50
當我在瀏覽器中嘗試時,這甚至不起作用。 Chrome,Firefox等用%20替換空格並且可行。 – ashishduh 2014-11-06 17:00:14
文件名是「something.example.com This File.pdf」? – iheanyi 2014-11-06 18:28:05