我想使用 intent.setData(Uri uri)
方法传递从URL获取到的数据。为了做到这一点,我需要能够从URL创建一个Uri(或者从我从URL读取的byte[]
或从byte[]
创建的ByteArrayInputStream
等)。然而,我不知道应该如何实现。
所以,有没有办法在不先将数据写入本地文件的情况下从从URL获取的数据创建 Uri?
使用URL.toURI()
方法(Android文档)。
示例:
URL url = new URL("http://www.google.com"); //Some instantiated URL object
URI uri = url.toURI();
一定要处理相关的异常,例如URISyntaxException
。
我认为你的答案可以在这里找到...
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
yourUrlVariable.toString()
来代替硬编码的 "http://..."。 - dmonString thisUrl = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=[redacted]&mapid=value"
方法:
private Uri.Builder builder;
public Uri getUriFromUrl(String thisUrl) {
URL url = new URL(thisUrl);
builder = new Uri.Builder()
.scheme(url.getProtocol())
.authority(url.getAuthority())
.appendPath(url.getPath());
return builder.build();
}
try {
uri = new URI(url.toString());
} catch (URISyntaxException e) {
}