Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a URI using URIbuilder without encoding hash

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

like image 453
kittu Avatar asked Feb 25 '16 12:02

kittu


2 Answers

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.

like image 54
wero Avatar answered Sep 27 '22 19:09

wero


Instead of all the hassle of redirecting without encoding the hash value. I changed my code into the following:

java.net.URI location = new java.net.URI("../#/Login?token=" + token);

So the query param above is token appended to URI location. In front-end I am using angular's location.search().token to get capture the query param.

This worked for me. Looking for better answers though. Thanks

like image 35
kittu Avatar answered Sep 27 '22 18:09

kittu