2014-09-23 53 views
1
try { 
    int count; 
    URL url = new URL("http://www.exampleserver.com/file names.txt"); 
    URLConnection connection = url.openConnection(); 
    connection.setReadTimeout(TIMEOUT_CONNECTION); 
    connection.setConnectTimeout(TIMEOUT_SOCKET); 
    connection.setRequestProperty("connection", "close"); 
    connection.connect(); 
    int lengthOfFile = connection.getContentLength(); 
    long total = 0; 
    InputStream input = new BufferedInputStream(url.openStream()); 
    OutputStream output = new FileOutputStream(BasindaOneCikanDosyalar); 
    byte data[] = new byte[40096]; 
    while ((count = input.read(data)) != -1) { 
     total += count; 
     output.write(data, 0, count); 
    } 
    output.flush(); 
    output.close(); 
    input.close(); 
} catch (IOException e1) { 
    e1.printStackTrace(); 
} 

我使用這個算法,但如果文件名包含空格,我java.io.FileNotFoundExceptiongetResponseCode:400如果文件名包含空格,我們如何使用URLConnection在android下載?

是否有庫或下載URL的不同算法?

回答

0

你需要編碼的URL您的文件名部分:

String encodedFilename = URLEncoder.encode(filename, "UTF-8").replace("+", "%20"); 
URL url = new URL("http://www.exampleserver.com/" + encodedFilename); 
+0

這是真棒,謝謝,我會嘗試 – massaimara98 2014-09-23 23:39:17

+0

我試過了,謝謝你,我可以繼續我的工作 – massaimara98 2014-09-23 23:53:54

+0

這是不正確的。儘管它的名字是,'URLEncoder'用於編碼參數名稱和值,而不是URL,正如你可以從這裏的'%20'的後期調整中看出的那樣。 @ PeterPeiGuo的回答給出了正確的技巧。 – EJP 2014-09-24 00:12:11

3

你需要躲避URL,並使其像下面這樣:

http://www.exampleserver.com/file%20names.txt 

在你的代碼做這樣的事情:

URI uri = new URI("http", "www.exampleserver.com", "/file names.txt", null); 
URL url = uri.toURL(); 
+0

您的意思是當我看到空格時,轉換爲「%20」? – massaimara98 2014-09-23 23:37:16

+1

是的,但有更多的規則,所以最好的是使用我上面的代碼,這是爲你做的 - 我更新了答案。 – 2014-09-23 23:38:09

相關問題