【问题标题】:How to handle empty space in url when downloading image from web?从网络下载图像时如何处理 url 中的空白空间?
【发布时间】:2011-12-20 07:13:43
【问题描述】:

我正在做一个项目,其中 url 有时可能有空格(并非总是)例如:www.google.com/example/test.jpg 有时是 www.google.com/example/test.jpg .

我的代码:

     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 input = new BufferedInputStream(url.openStream(), 8192);

带有:java.io.FileNotFoundException。

我已尝试对特定行进行编码,但问题在于:服务器需要空白空间“”才能找到文件,因此我需要以某种方式获得空白空间。如果我使用 firefox 浏览器,我可以找到文件 (jpg)。 非常感谢任何帮助。

编辑更新: 好吧,现在我尝试将 url 的主机部分之后的每一位编码为 utf-8,并且我尝试使用 + 和 %20 作为空白空间。现在我可以设法对文件进行 DL,但它会出现故障,因此无法读取。

编辑更新2: 我在 %20 上犯了一个错误,这行得通。

【问题讨论】:

  • 只是好奇...你有什么服务器?我猜“example”和“example”是目录,大多数操作系统不允许在文件名的末尾和开头有空格。
  • 我不确定我是否理解您的问题。但是你为什么不直接替换空格
  • 这是一个客户服务器,没有任何意义,这个问题出现了;)但确实如此。我试过只用空格,但找不到文件,也找不到编码的八字,所以有什么想法吗?
  • 你试过用 %20 或 + 替换空格吗?
  • 已编码

标签: android url bufferedinputstream


【解决方案1】:

好的,我解决了头痛。

首先我使用:

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。请参阅 Powerlord 的 Trouble Percent-Encoding Spaces in Java 评论

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2020-10-20
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多