Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep baseUrl when using uri() in spring webflux

Using spring boot 2.1.3.RELEASE, WebClient will stop using the provided baseUrl when passing an URI to uri() method. It will keep baseUrl when a string is passed to uri() though.

How can I provide a baseUrl and pass an URI?

public WebClient webClient() {
  return WebClient.builder()
    .baseUrl("https://example.com/")
    .build();
}

and

webClient.get().uri(URI.create("/foo/%23bar"))... 

throws

java.lang.IllegalArgumentException: URI is not absolute:

and the request url becomes

request url: /foo/%23bar
like image 845
baao Avatar asked Feb 17 '19 12:02

baao


2 Answers

If you pass new URI Object, you override base URI. You should use uri method with lambda as a parameter, like in example:

final WebClient webClient = WebClient
  .builder()
  .baseUrl("http://localhost")
  .build();
webClient
  .get()
  .uri(uriBuilder -> uriBuilder.pathSegment("api", "v2", "json", "test").build())
  .exchange();
like image 119
Konstantin Pozhidaev Avatar answered Sep 28 '22 02:09

Konstantin Pozhidaev


A slightly different way - use path instead of pathSegment on existing uri object. It helps to maintain the path conveniently in configuration/constant form.

final WebClient webClient = WebClient
.builder()
.baseUrl("http://localhost")
.build();
webClient
.get()
.uri(uriBuilder -> uriBuilder.path("api/v2/json/test").build())
.exchange();
like image 30
Prosunjit Biswas Avatar answered Sep 28 '22 04:09

Prosunjit Biswas