Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Webflux WebClient

I don't really know how to translate the following call to the spring webflux webclient correctly.

userIds is the List and I was able to call the service using the following syntax but I could not get that working with the Spring WebFlux WebClient. Please help me if there is any of you know how to do it.

String url = "http://profile.service.com/v1/profiles/bulk";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

ResponseEntity<List<MiniProfile>> responseEntity;
try {
    responseEntity = restTemplate.exchange(url, HttpMethod.POST, new 
    HttpEntity(userIds, headers), new 
    ParameterizedTypeReference<List<MiniProfile>>() {});
} catch (RestClientException e) {
    responseEntity = new ResponseEntity<List<MiniProfile>>(HttpStatus.OK);
}

return responseEntity.getBody();

This is the way I got it translate to the Webflux WebClient:

Flux<String> flux = Flux.fromIterable(userIds);
return readWebClient.post().uri("/v1/profiles/bulk")
      .body(BodyInserters.fromPublisher(flux, String.class))
      .retrieve().bodyToFlux(MiniProfile.class);
like image 980
Eric Nguyen Avatar asked Dec 09 '25 01:12

Eric Nguyen


2 Answers

You should not change your list to flux, you should send it as list like this

return readWebClient.post()
  .uri("/v1/profiles/bulk")
  .syncBody(userIds)
  .retrieve()
  .bodyToFlux(new ParameterizedTypeReference<List<MiniProfile>>() {})
  .flatMapIterable(Function.identity());

this code is not tested but the principe is the same

like image 112
hishammuddin-sani Avatar answered Dec 11 '25 22:12

hishammuddin-sani


It's good to use WebClient for reactive call such this.

@Autowired
private WebClient.Builder webClientBuilder;
webClientBuilder.build().post()
                .uri("http://profile.service.com/v1/profiles/bulk")
                .body(BodyInserters.fromPublisher(Mono.just(new YourBodyClass()),YourBodyClass.class))
                .headers(httpHeaders -> {
                    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                    httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
                })
                .retrieve().bodyToFlux(MiniProfile.class);
like image 24
Saman Sarem Avatar answered Dec 11 '25 22:12

Saman Sarem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!