Skip to content Skip to sidebar Skip to footer

Is It Possible To Use Uri.builder And Not Have The "//" Part?

I am trying to build a mailto: uri to send a mail using the GMail app. I would like to use the android.net.Uri.Builder class to do this, but the resulting uri is in the form mailto

Solution 1:

There are several issues here. While it is possible to get rid of the // part, you will loose the query strings then. The main problem is that Uri.Builder won't let you use queries with opaque URIs (an opaque URI is an absolute URI whose scheme-specific part does not begin with a slash character, like mailto: URIs).

That said, you should use uriBuilder.opaquePart() instead of uriBuilder.authority() because the latter implicitly sets your URI to hierarchical, i.e. non-opaque. This will get rid of the //, but you're lacking the query part then, and you cannot set it, because any call to uriBuilder.appendQueryParameter() also implies a hierarchical URI.

Long story short, to construct an opaque mailto: URI that includes queries, you'll have to use

Uriuri= Uri.parse("mailto:receipient@mail.com?subject=title&body=text");

instead. Of course, the literal title and text should be Uri.encode()ed.

Solution 2:

The answer given by sschuberth is a good explanation of what's going on, but as a more practical answer (you do want to properly escape parameters, etc. after all), I used two builders to get around this:

Builderbuilder1=newBuilder();
builder1.scheme("mailto");
builder1.opaquePart(emailAddress);

Builderbuilder2=newBuilder();
builder2.appendQueryParameter("subject", subject);
builder2.appendQueryParameter("body", body);

Uriuri= Uri.parse(builder1.toString() + builder2.toString());

You probably don't want to do this in a tight loop with millions of addresses, but for general use I think this should be fine.

Solution 3:

sschuberth's answer is much briefer than kabuko's, so here's a variant that also covers encoding:

Uri uri = Uri.parse(
    String.format("mailto:%s?subject=%s",
        Uri.encode(recipient),
        Uri.encode(subject)
    )
);

Post a Comment for "Is It Possible To Use Uri.builder And Not Have The "//" Part?"