Search code examples
spring-bootjava-8webclientspring-webfluxspring-webclient

Trying to Send list of string in post request using webClient in spring


  • I am trying to send a list of strings using webClient but I am getting an exception.

  • I used Flux.fromIterable(strList) but it merged all the data before sending, because of that instead of a list of strings I received combined single string on mapping class.

     List<String> str = new ArrayList<>();
                 str.add("korba");
                 str.add("raipur");
                 str.add("bhilai");
    
       Flux<Object> responsePost = webClient.build()
                          .post()
                          .uri(url)
                          .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                          .body(Flux.fromIterable(str), String.class)
                          .retrieve()
                          .bodyToFlux(Object.class);
    

Solution

  • You cannot send a Flux of strings because it combines them into a single string. See,

    WebClient bodyToFlux(String.class) for string list doesn't separate individual value

    You are creating a Flux of strings at Flux.fromIterable(str). What you need to do is put the string into a wrapper class or send a Mono of a list. See, e.g., Reactive Programming: Spring WebFlux: How to build a chain of micro-service calls?