如何从java.net.URL创建android.net.Uri?

2022-09-01 15:04:22

我想传递从 URL 获取的数据。为了做到这一点,我需要能够从URL(或从我从URL读取的byte[],或我从中创建的字节[]创建URI等)创建URI。但是,我无法弄清楚应该如何做到这一点。use intent.setData(Uri uri)ByteArrayInputStreambyte[]

那么,是否无论如何都可以从从URL获取的数据中创建Uri,而无需先将数据写入本地文件?


答案 1

使用 URL.toURI()Android doc) 方法。

例:

URL url = new URL("http://www.google.com"); //Some instantiated URL object
URI uri = url.toURI();

确保处理相关的异常,例如 URISyntaxException


答案 2

我想你的答案可以从这里找到。

Uri.Builder.build()与普通URL一起工作得很好,但在端口号支持下会失败。

我发现让它支持端口号的最简单方法是让它首先解析一个给定的URL,然后使用它。

Uri.Builder b = Uri.parse("http://www.yoursite.com:12345").buildUpon();

b.path("/path/to/something/");
b.appendQueryParameter("arg1", String.valueOf(42));

if (username != "") {
  b.appendQueryParameter("username", username);
}

String url = b.build().toString(); 

来源 : http://twigstechtips.blogspot.com/2011/01/android-create-url-using.html


推荐