从网上下载图片时如何处理网址中的空白区域?

时间:2011-11-02 12:47:56

标签: android url bufferedinputstream

我正在开展一个项目,其中网址有时会有空格(并非总是如此)示例: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的错误,这有效。

1 个答案:

答案 0 :(得分: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的Trouble Percent-Encoding Spaces in Java评论