I am struggling to understand the behavior of UriComponentsBuilder
. I want to use it to encode a URL in a query parameter, however it appears to only escape %
characters, but not other necessary characters such as &
.
An example of a URL in a query parameter that is not encoded at all:
UriComponentsBuilder.fromUri("http://example.com/endpoint")
.queryParam("query", "/path?foo=foo&bar=bar")
.build();
Output: http://example.com/endpoint?query=/path?foo=foo&bar=bar
This is not correct, because the unencoded &
causes bar=bar
to be interpreted as a query parameter to /endpoint
instead of /path
.
However, if I use an input that contains a %
character::
UriComponentsBuilder.fromUri("http://example.com/endpoint")
.queryParam("query", "/path?foo=%20bar")
.build();
Output: http://example.com/endpoint?query=/path?foo=%2520bar
The %
character is escaped.
It seems inconsistent that UriComponentsBuilder
would automatically escape the %
characters but not the other reserved characters.
What is the correct process to encode a URL into a query parameter with UriComponentsBuilder
?
&
is a valid character in URL. Barring certain characters, everything else must be url encoded. – Strove