DIfference between Uri.fromParts and Uri.parse?

2019-08-27 09:38发布

I'm creating an Intent for Android, to send e-mails.

And I'm getting confused about the behavior of Uri.fromParts.

Mi code: This works fine!

uri=Uri.parse(
  "mailto:" + toAddress +
    (subject != null ?
      ("?" + "subject=" + Uri.encode(subject)) :
      "")

The previous work fine, and create an Uri in the form "mailto:john@doe.com?subject=Test

But if I try to use Uri.from parts, with this sample:

uriBuilder=Uri.fromParts("mailto",toAddress,null).buildUpon();
if (subject!=null) {
    uriBuilder.appendQueryParameter("subject",subject);
}
uri=uriBuilder.build();

I get an error. The final uri is mailto:?subject=Test

The intermediate is correct, but when I use appendQueryParameter, it removes the content after the mailto scheme.

Do you know why? Which is the canonical way to do this?

1条回答
放我归山
2楼-- · 2019-08-27 09:53

Uri#fromParts()

Creates an opaque Uri from the given components. Encodes the ssp which means this method cannot be used to create hierarchical URIs.

When you call buildUpon() on this, the Builder contains the scheme, scheme-specific part (ssp) and the fragment (null in your case).

appendQueryParameter() then turns the Builder to a hierarchical one, deleting the opaque ssp data.

I don't think there's a "canonical" way. Just don't mix hierarchical and opaque builders.

For details on what happens under the hood, read the source.

查看更多
登录 后发表回答