安卓:HOWTO解析URL字符串空格的URI对象? [英] Android: howto parse URL String with spaces to URI object?

查看:378
本文介绍了安卓:HOWTO解析URL字符串空格的URI对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串再presenting包含空格的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

其中,指数 X 是URL字符串的第一个空间的位置。

where index X is the position of the first space in the URL string.

我怎样才能解析 myString的 URI 对象?

How can i parse myStringinto a URI object?

推荐答案

其实你应该 URI恩code 中的无效字。由于该字符串实际上包含了完整的URL,这是很难正确的URI连接code吧。你不知道哪个斜线 / 应考虑到,哪些不是。你不能pdict了事先$ P $在原始字符串。这个问题确实需要在更高层次上得到解决。在这情况下字符串从何而来?它是很难codeD?然后,你来就可以相应地改变它。它进来作为用户输入?验证它,并显示错误,让用户自行解决。

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恩codeD,那么你也可以只是这样做与<帮助href="http://developer.android.com/reference/android/net/Uri.html#en$c$c(java.lang.String)"><$c$c>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)));

请注意, URLEn codeR 是insuitable的任务,因为它的设计EN code查询字符串参数名称/值按应用程序/的X WWW的形式 - urlen codeD 规则(如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.

这篇关于安卓:HOWTO解析URL字符串空格的URI对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆