2011-11-02 88 views
2

我正在开发一个项目,其中url有时可以有空格(不总是),例如:www.google.com/ example/test.jpg,有时还有www.google.com/example/test.jpg。如何在从网站下载图像时处理URL中的空白空间?

我的代码:

 try { 
      URL url = new URL(stringURL); 
      URLConnection conexion = url.openConnection(); 
      conexion.connect(); 

      // downlod the file 
      InputStream input = new BufferedInputStream(url.openStream(), 8192); 
      OutputStream output = new FileOutputStream(fullPath.toString()); 

      byte data[] = new byte[1024]; 

      while ((count = input.read(data)) != -1) { 
       output.write(data, 0, count); 
      } 
      output.flush(); 
      output.close(); 
      input.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

这是此行失败:InputStream的输入=新的BufferedInputStream(url.openStream(),8192);

带有:java.io.FileNotFoundException。

我试过编码特定的行,但这里是踢脚板:服务器需要空的空间“”才能找到文件,所以我需要有空的空间。如果我使用Firefox浏览器,我可以找到文件(jpg)。 任何帮助非常感谢。

编辑更新: 好了,现在我已经尝试将URL的主机部分之后的每一位都编码为utf-8,并且我已经尝试了将+和%20同时用于空格。现在我可以管理DL文件,但它会有问题,因此无法读取。

编辑更新2: 我犯了%20错误,这是有效的。

+0

只是好奇...你有什么服务器?我猜“example”和“example”是目录,而且大多数操作系统在文件名的末尾和开头都不允许有空格。 – Cristian

+0

我不确定我是否理解你的问题。但是,为什么你不只是替换空的空间 – Shadow

+0

这是一个客户服务器,没有认识到这个问题出现;)但它确实如此。我已经尝试过只是空的空间,但它无法找到该文件,并找不到与编码的打火机,所以任何想法? – Warpzit

回答

2

好吧,我解决了头痛。

首先,我用:

completeUrl.add(URLEncoder.encode(finalSeperated[i], "UTF-8")); 

对于之间的网址的每一部分 “/”

然后我用:

ArrayList<String> completeUrlFix = new ArrayList<String>(); 
    StringBuilder newUrl = new StringBuilder(); 
    for(String string : completeUrl) { 
     if(string.contains("+")) { 
      String newString = string.replace("+", "%20"); 
      completeUrlFix.add(newString); 
     } else { 
      completeUrlFix.add(string); 
     } 
    } 

    for(String string : completeUrlFix) { 
     newUrl.append(string); 
    } 

要建立一个适当的urlString。

这个原因起作用的原因是因为http需要%20。查看Trouble Percent-Encoding Spaces in Java评论人Powerlord