我试图检索文件名中带有元音变音的网址,例如“http://somesimpledomain.com/some/path/überfile.txt”,但它给了我一个java.io.FileNotFoundException。我怀疑远程服务器上的文件名是用 latin1 编码的,尽管我的 url 是 utf8 编码的。但我尝试更改 url 的编码没有成功,我不知道如何进一步调试它。请帮忙!
代码如下:
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(uri).openConnection();
conn.setRequestMethod("GET");
} catch (MalformedURLException ex) {}
} catch (IOException ex){}
// Filter headers
int i=1;
String hKey;
while ((hKey = conn.getHeaderFieldKey(i)) != null) {
conn.getHeaderField(i);
i++;
}
// Open the file and output streams
InputStream in = null;
OutputStream out = null;
try {
in = conn.getInputStream();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
out = response.getOutputStream();
} catch (IOException ex) {
}
问候, 亨德里克
最佳答案
URL 需要正确编码。您必须知道您的服务器期望什么字符集/编码。你可以先试试这个,
String uri = "http://somesimpledomain.com/some/path/" +
URLEncoder.encode(filename, "ISO-8859-1");
如果这不起作用,请将“ISO-8859-1”替换为“UTF-8”,然后重试。
如果这也不起作用,则文件不存在:)
关于检索文件名中包含变音符号的 url 时出现 java.io.FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1455369/