我正在做一个项目,其中 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 上犯了一个错误,这行得通。
最佳答案
好吧,我解决了头痛问题。
首先我使用:
completeUrl.add(URLEncoder.encode(finalSeperated[i], "UTF-8"));
对于“/”之间的 url 的每一部分
然后我使用:
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霸王评论
关于android - 从网络下载图片时如何处理url中的空白区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7980552/