Android:如何解析带有空格的URL String到URI对象? [英] Android: how to parse URL String with spaces to URI object?
问题描述
我有一个表示包含空格的URL的字符串,并希望将其转换为URI对象。如果很简单,请尝试
I have a string representing an URL containing spaces and want to convert it to an URI object. If is simple try to do
String myString = "http://myhost.com/media/mp3s/9/Agenda of swine - 13. Persecution Ascension_ leave nothing standing.mp3";
URI myUri = new URI(myString);
它给了我
java.net.URISyntaxException: Illegal character in path at index X
其中index X
是URL字符串中第一个空格的位置。
where index X
is the position of the first space in the URL string.
我如何解析 myString
进入 URI
对象?
推荐答案
事实上,您应该 URI编码无效字符。由于字符串实际上包含完整的URL,因此很难对其进行正确的URI编码。你不知道应该考虑哪些斜杠 /
,哪些不应该考虑。您无法预先在原始字符串
上预测。问题确实需要在更高层次上解决。那个 String
来自哪里?它是硬编码的吗?然后相应地自己更改。它是否以用户输入的形式出现?验证它并显示错误,让用户自行解决。
You should in fact URI-encode the "invalid" characters. Since the string actually contains the complete URL, it's hard to properly URI-encode it. You don't know which slashes /
should be taken into account and which not. You cannot predict that on a raw String
beforehand. The problem really needs to be solved at a higher level. Where does that String
come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.
无论如何,如果你能确保它只是 那么URL中的空格这使得它无效,那么你也可以用%20
进行逐字符串替换:
At any way, if you can ensure that it are only the spaces in URLs which makes it invalid, then you can also just do a string-by-string replace with %20
:
URI uri = new URI(string.replace(" ", "%20"));
或者如果你可以确保它只是 最后一个斜杠之后的部分需要进行URI编码,然后你也可以在 android.net.Uri
实用程序类:
Or if you can ensure that it's only the part after the last slash which needs to be URI-encoded, then you can also just do so with help of android.net.Uri
utility class:
int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + Uri.encode(string.substring(pos)));
请注意 URLEncoder
对于任务是不可或缺的,因为它设计用于编码查询字符串参数名称/值按 application / x-www-form-urlencoded
规则(在HTML表单中使用)。另请参阅查询字符串参数的Java URL编码。
Do note that URLEncoder
is insuitable for the task as it's designed to encode query string parameter names/values as per application/x-www-form-urlencoded
rules (as used in HTML forms). See also Java URL encoding of query string parameters.
这篇关于Android:如何解析带有空格的URL String到URI对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!