Search code examples
androiduriurlencodehashtaguribuilder

How to create Android Uri with hashtag in the center


I have the following Uri I want to construct.

https://www.example.com/sub/#/action?firstparam=123456&secondparam=abcdef

I use the Android Uri.Builder to construct the Uri

Uri uri = new Uri.Builder().scheme(HTTPS_SCHEME).authority("www.example.com").appendPath("sub").appendPath("#").appendPath("action")appendQueryParameter(
            "firstparam", first).appendQueryParameter("secondparam", second).build();

But the hashtag is encoded and will result in the following Uri

https://www.example.com/sub/%23/action?firstparam=123456&secondparam=abcdef

How to prevent this? I tried using fragment but it adds the hashtag at the end of the Uri.


Solution

  • That's how Uri.Builder works. It encodes non-safe URL characters with special meaning to their hex values. In your case # is encoded as %23

    To prevent this use:

    builder.appendEncodedPath("#")