Correct URL encoding of # Java WebClient

Viewed 1574

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

1 Answers

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