Android:如何将带有空格的 URL 字符串解析为 URI 对象? [英] Android: how to parse URL String with spaces to URI object?

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

问题描述

我有一个表示包含空格的 URL 的字符串,并希望将其转换为 URI 对象.如果我只是尝试通过

I have a string representing an URL containing spaces and want to convert it to an URI object. If I simply try to create it via

String myString = "http://myhost.com/media/File Name that has spaces inside.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 对象?

How can i parse myString into a URI object?

推荐答案

事实上你应该 URI-编码无效"字符.由于字符串实际上包含完整的 URL,因此很难对其进行正确的 URI 编码.您不知道哪些斜杠 / 应该被考虑在内,哪些不应该被考虑在内.您无法事先在原始 String 上预测.这个问题确实需要在更高的层次上解决.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 字符串解析为 URI 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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