Search code examples
spring-booturispring-webfluxspring-webclienturibuilder

How to build URI with UriBuilder without specifying scheme, host separately?


Ref: org.springframework.web.util.UriBuilder

I am using UriBuilder to build a URI for an endpoint

final String response = myWebClient.get()
   .uri(uriBuilder -> uriBuilder.scheme("https").path("example.com/mypage").path("/{id}.xml").build(id))
   .header(AUTHORIZATION, getAuthorizationHeaderValue(username, password))
   .accept(MediaType.TEXT_XML)
   .retrieve()
   .bodyToMono(String.class)
   .block();

However, I already have the value https://example.com/mypage in a string variable(fetched from the database). Can I use this string directly instead of specifying the scheme and path/host separately? Right now I am splitting the main string into individual parts manually.


Solution

  • You can use UriComponentsBuilder to build an URI :

    URI uri = UriComponentsBuilder.fromHttpUrl("https://example.com/mypage").path("/{id}.xml").build(id);
    
    myWebClient.get()
     .uri(uri)
     .header(AUTHORIZATION, getAuthorizationHeaderValue(username, password))
     ....
    

    Alternatively, if the HTTP requests that you need to sent out have some common settings(i.e. base url and Authorization header in your case) , you can configure them at the WebClient.Builder level. The WebClient build by this builder will be configured with these common setting by default such that you do not need to configure them again and again for each HTTP request. Something like:

    @Component 
    public class ExampleComClient {
    
    
        private final WebClient webClient;
    
        @Autowired
        public ExampleComClient(WebClient.Builder builder) {
            this.webClient = builder.baseUrl("https://example.com/mypage")
                                .defaultHeader(AUTHORIZATION, getAuthorizationHeaderValue(username, password))
                                .build();
        }
    
        public String getById(Integer id){
    
           return webClient.get()
                    .uri(uriBuilder -> uriBuilder.path("/{id}.xml").build(id))      
                   .accept(MediaType.TEXT_XML)
                   .retrieve()
                   .bodyToMono(String.class)
                   .block();
        }
    
    
         public String getByName(String name){
    
           return webClient.get()
                    .uri(uriBuilder -> uriBuilder.queryParam("name",name).build())      
                   .accept(MediaType.TEXT_XML)
                   .retrieve()
                   .bodyToMono(String.class)
                   .block();
        }
    
    }