UriBuilder encoding issue with queryParam

1.5k Views Asked by At
var responseEntity =
          webClient
              .get()
              .uri(
                  uriBuilder ->
                      uriBuilder
                          .path("myendpoint")
                          .queryParam("email", email)
                          .build())
              .retrieve()

The problem with this code is that if the email here is like [email protected], the URI default encoding doesn't encode + in the queryParam, and if I myself encode the string to Proper Uri encoded string: like: my%[email protected], in this case, URI default encoder here will encode the % symbol as well. Now, if I use the .encode() function of uriBuilder, it would also encode @ in the email.

I want to achieve URI like: https://myendpoint?email=my%[email protected]

Can somebody please help with this? Thanks a lot.

2

There are 2 best solutions below

0
Kartik Arora On BEST ANSWER

The param within build(boolean encoded) function of UriComponentsBuilder actually define if a URI is already encoded and prevent double encoding of the params again, so we can pass an encoded email to the param and prevent any encoding to be run on that email through the uriBuilder itself.

 var responseEntity =
          webClient
              .get()
              .uri(
                  uriBuilder ->
                      UriComponentsBuilder.fromUri(uriBuilder.build())
                          .path("myendpoint")
                          .queryParam("email", getEncodedEmail(email))
                          .build(true)
                          .toUri())
              .retrieve();
private String getEncodedEmail(String email){
    return URLEncoder.encode(email, StandardCharsets.UTF_8).replace("%40","@");
  }
3
MarcelMM On

You can instanciate the URI this way:

URI.create("myendpoint?email=" + URLEncoder.encode("[email protected]", StandardCharsets.UTF_8).replace("%40", "@"))

It's not very elegant but it works.