2

我正在做一个项目,其中 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,但它会出现故障,因此无法读取。

编辑 update2:我在 %20 上犯了一个错误,这很有效。

4

1 回答 1

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

于 2011-11-02T19:49:56.517 回答