4

I'm tring to use this code to retrieve data from my API:

        Mono<String> client = WebClient.builder()
          .baseUrl("https://localhost:8081/getPost/" + id) // or URLEncoder.encode(id, "UTF-8")
          .defaultHeaders(new Consumer<HttpHeaders>() {
              @Override
              public void accept(HttpHeaders httpHeaders) {
                httpHeaders.addAll(createHeaders());
              }
            })
          .build()
          .get()
          .retrieve()
          .bodyToMono(String.class);

My Ids starts with '#' so if I use this code it will result in:

https://localhost:8081/getPost/#id1

The problem is that I need it url encoded so it should be getPost/%23id1, I tried to use URLEncoder on id but the result is double encoded:

 https://localhost:8081/getPost/%25%23id1

I need to get rid of that %25

Erry215
  • 326
  • 1
  • 4
  • 15
  • 1
    I am sorry but I think you can't .. The %23 is due the fact # is a [reserved character](https://en.wikipedia.org/wiki/Percent-encoding) (some reference [here](https://stackoverflow.com/questions/5007352/how-to-escape-hash-character-in-url) and [here](https://stackoverflow.com/questions/19787525/how-to-escape-symbol-in-url)). Hope I helped you – gianluca aguzzi Apr 14 '21 at 15:00
  • I know that # is reserved but if I use the code above the url will result in /#id while I need /%23id. I'm using the same API on php and I encode # with %23. I don't know why Java allows # char without encoding – Erry215 Apr 14 '21 at 16:39
  • Sorry I didn't get to the point but you were very clear. This behaviour is very strange. I have tried to reproduce your code [here](https://replit.com/talk/share/example/134965) and it seems to work. %25 stands for %, is there something like that in your id string? – gianluca aguzzi Apr 14 '21 at 19:58

1 Answers1

6

It seems strange that WebClient.builder().baseUrl fails to correctly encode the reserved character "#". If you look at the doc, it says it's equivalent to .uriBuilderFactory(new DefaultUriBuilderFactory(baseUrl)). Therefore, you can do your own URL encoding, but suppress it in WebClient:

DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(
        "https://localhost:8081/getPost/" + URLEncoder.encode(id, "UTF-8"));
factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT);
Mono<String> client = WebClient.builder()
          .uriBuilderFactory(factory)
          .defaultHeaders(...)
          .build()
          ...etc...
k314159
  • 5,051
  • 10
  • 32