编码包含unicode字符的URL

时间:2013-03-19 22:32:58

标签: android-networking

是否存在(正确)编码包含unicode字符的URL的Android类?例如:

Blue Öyster Cult

使用java.net.URI转换为以下内容:

uri.toString()
 (java.lang.String) Blue%20Öyster%20Cult

Ö字符未编码。使用URLEncoder

URLEncoder.encode("Blue Öyster Cult", "UTF-8").toString()
 (java.lang.String) Blue+%C3%96yster+Cult

它编码太多(即空格变为“+”,路径分隔符“/”变为%2F)。如果我使用Dolphin Web浏览器单击包含unicode字符的链接,它可以正常工作,所以显然可以这样做。但是如果我尝试使用上述任何字符串打开HttpURLConnection,我会得到HTTP 404 Not Found例外。

2 个答案:

答案 0 :(得分:2)

我最终破解了一个似乎对此有用的解决方案,但可能不是最强大的:

url = new URL(userSuppliedPath);
String context = url.getProtocol();
String hostname = url.getHost();
String thePath = url.getPath();
int port = url.getPort();
thePath = thePath.replaceAll("(^/|/$)", ""); // removes beginning/end slash
String encodedPath = URLEncoder.encode(thePath, "UTF-8"); // encodes unicode characters
encodedPath = encodedPath.replace("+", "%20"); // change + to %20 (space)
encodedPath = encodedPath.replace("%2F", "/"); // change %2F back to slash
urlString = context + "://" + hostname + ":" + port + "/" + encodedPath;

答案 1 :(得分:1)

URLEncoder旨在用于编码表单内容,而不是整个URI。编码/为%2F是为了防止用户输入被解释为目录,而+是表单数据的有效编码。 (表单数据==后面的URI的一部分?)

理想情况下,在将附加到基本URI之前编码“BlueÖysterCult”,而不是编码整个字符串。如果“BlueÖysterCult”是路径的一部分而不是查询字符串的一部分,则必须自己用%20替换+。有了这些限制,URLEncoder工作正常。