How to build a URI using URIbuilder without encoding hash

kittu picture kittu · Feb 25, 2016 · Viewed 12.7k times · Source

I have a URI like this:

java.net.URI location = UriBuilder.fromPath("../#/Login").queryParam("token", token).build();

and I am sending it as response: return Response.seeOther(location).build()

However, in the above URI, # is getting encoded to %23/. How do I create a URI with out encoding the hash #. According to official document, a fragment() method must be used to keep unencoded.

URI templates are allowed in most components of a URI but their value is restricted to a particular component. E.g.

UriBuilder.fromPath("{arg1}").build("foo#bar"); would result in encoding of the '#' such that the resulting URI is "foo%23bar". To create a URI "foo#bar" use UriBuilder.fromPath("{arg1}").fragment("{arg2}").build("foo", "bar") instead.

Looking at the example from docs, I am not sure how to apply it in my case.

The final URI should look like this:

http://localhost:7070/RTH_Sample14/#Login?token=eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvcnRoLmNvbSIsInN1YiI6IlJUSCIsInJvbGUiOiJVU0VSIiwiZXhwIjoxNDU2Mzk4MTk1LCJlbWFpbCI6Imtpcml0aS5rOTk5QGdtYWlsLmNvbSJ9.H3d-8sy1N-VwP5VvFl1q3nhltA-htPI4ilKXuuLhprxMfIx2AmZZqfVRUPR_tTovDEbD8Gd1alIXQBA-qxPBcxR9VHLsGmTIWUAbxbyrtHMzlU51nzuhb7-jXQUVIcL3OLu9Gcssr2oRq9jTHWV2YO7eRfPmHHmxzdERtgtp348

Answer

wero picture wero · Feb 25, 2016

To construct the URI with fragment use

UriBuilder.fromPath("http://localhost:7070/RTH_Sample14/").fragment("Login").build()

This results in the URI string

http://localhost:7070/RTH_Sample14/#Login

But if you also add query parameters

UriBuilder.fromPath("http://localhost:7070/RTH_Sample14/").fragment("Login")
          .queryParam("token", "t").build()

then the UriBuilder always inserts the query params before the fragment:

http://localhost:7070/RTH_Sample14/?token=t#Login

which simply complies to the URL syntax.