javaspringuriurlencodeuribuilder

UriBuilder encoding issue with queryParam


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 my+email@gmail.com, the URI default encoding doesn't encode + in the queryParam, and if I myself encode the string to Proper Uri encoded string: like: my%2Bemail@gmail.com, 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%2Bemail@gmail.com

Can somebody please help with this? Thanks a lot.


Solution

  • 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","@");
      }