Uri Builder in android - '/' replaced by '%2F' and ":" is replaced by "%3A"

13,864

Solution 1

That's how Uri.Builder works. It encodes non-safe URL characters with special meaning to their %xx hex values.

To prevent encoding URI parts that are already properly encoded, use the encoded versions of builder functions:

builder.encodedAuthority(host);
builder.appendEncodedPath(service + "/" +method);

But since all your URL parts are already ready and don't need any further encoding, it's easier to just use a regular StringBuilder to concatenate the parts.

Solution 2

Like laalto said, this is how Uri.Builder works but if you want to get the uri in a regular url form, like in your case: https://10.112.88.182:8443/Vehicle/services/socialService/login you can do:

URL url = new URL(URLDecoder.decode(builder.build().toString(), "UTF-8"));

Solution 3

The solution is quite simple, simply use appendEncodedPath(), it will not encode your string, it just appends it as it is.

Share:
13,864

Related videos on Youtube

Manik
Author by

Manik

Updated on May 25, 2022

Comments

  • Manik
    Manik almost 2 years

    I want to build the following URI -

    https://10.112.88.182:8443/Vehicle/services/socialService/login
    

    ...

    Builder builder = new Builder();
    builder.scheme(Constants.URL_SCHEME);
    builder.authority(host);
    builder.appendPath(service + "/" +method);
    return builder.build().toString();
    

    where

    • URL_SCHEME - https
    • host - 10.112.88.182:8443/Vehicle/services/
    • service - socialService
    • method - login

    When this code runs I get the following URI -

    https://10.112.88.182%3A8443%2FVehicle%2Fservices%2F/socialService%2Flogin
    

    / is replaced by %2F and : is replaced by %3A

  • Manik
    Manik over 10 years
    then how will I be able to add ':' after my IP (before port 8443) ?
  • n8yn8
    n8yn8 over 8 years
    If host is set to 10.112.88.182:8443, then you could build your path so that it will be Vehicle/services/socialService/login which I believe can be done by .appendPath(Vehicle/services), plus additional .appendPath() or .appendEncodedPath() as needed.
  • Soren Stoutner
    Soren Stoutner about 7 years
    This is a great solution. Because the original request is trying to return a string, the best answer is simply return URLDecoder.decode(builder.build().toString(), "UTF-8");.
  • serv-inc
    serv-inc over 6 years
    How would you add something with a comma as a query parameter? appendQueryParameter("zipcode", "12346,US") encoded the ,.