Android URL到Uri


70

我必须将URL更改为URI,请指导我如何更改它。

我已经尝试了很多,但没有得到解决方案。任何帮助表示赞赏。如果需要,我还可以附加代码段。


Answers:


105

我们可以使用Uri.parse(String)方法解析任何URL。

代码段:

Uri uri =  Uri.parse( "http://www.stackoverflow.com" );

3
好吧,这将是String到Uri,而不是URL到Uri。
2014年

4
应该java.net.URI用还是android.net.Uri?有偏好吗?
某处某人2015年

32
final String myUrlStr = "xyz";
URL url;
Uri uri;
try {
    url = new URL(myUrlStr);
    uri = Uri.parse( url.toURI().toString() );
} catch (MalformedURLException e1) {
    e1.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}

1
乍一看,这个答案看起来很复杂。为什么要转换为字符串然后进行解析?原因是toURI()返回java.net.URI。因此,我们需要映射到字符串,然后解析为android.net.Uri。好的答案
tir38

0

这是我的2美分,它可以帮助别人。

如果您将变量作为查询传递给URL,那么标准URL解析可能不是一个好主意。

String your_url_which_is_not_going_to_change = "http://stackoverflow.com/?q="
String your_query_string = "some other stuff"
String query = null;

try {
  query = URLEncoder.encode(your_query_string, "utf-8");
} catch (UnsupportedEncodingException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

String url = your_url_which_is_not_going_to_change + query;

URL input = new URL(url);
etc... .

希望能帮助到你。

H。


1
他要求将URL解析为URI,但是您只是解析URL
IIRed-DeathII
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.