0
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.

Kartik Arora
  • 958
  • 1
  • 10
  • 17

2 Answers2

1

You can instanciate the URI this way:

URI.create("myendpoint?email=" + URLEncoder.encode("my+email@gmail.com", StandardCharsets.UTF_8).replace("%40", "@"))

It's not very elegant but it works.

MarcelMM
  • 175
  • 5
  • Hi, thanks for your answer, I had such implementation while trying some workarounds: ```java URI uri = factory.uriString("myendpoint").queryParam("email", "{email}").build(email); ``` Another problem here is though, my actual domain address won't come, it would only have the endpoint, but the actual URL should be: http://mydomain/myendpoint?email, and I don't want to hardcode mydomain, Is there some efficient way to achieve that? – Kartik Arora Mar 08 '23 at 05:26
  • I don't know if I understood correctly. But if the endpoint is not hardcoded, where is it going to be? Maybe you need to receive it as a parameter or use some strategy using ThreadLocal. Then put it all together with a StringBuilder. – MarcelMM Mar 08 '23 at 05:48
  • I have been able to solve the issue in a cleaner way, making use of the encoded param within the build function of UriComponentsBuilderf as i would be adding as an answer. – Kartik Arora Mar 08 '23 at 11:52
0

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","@");
  }
Kartik Arora
  • 958
  • 1
  • 10
  • 17