Home > other >  Consuming external api using webclient
Consuming external api using webclient

Time:05-21

I am having list of urls. I'm trying to consume jsondata from those api's. Below is the code which i tried but I'm getting Mono.flatMapMany-> at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultResponseSpec.bodyToFlux(DefaultWebClient.java:554)

If I use .block() I'm getting the jsonData for those api's but the thing is it becomes synchronous when i use .block(). I want it to be async. Can anyone help me out.

Thanks in advance.

List<String> urls=getUrls();
Flux<String> k=null;
for(int i=0;i<urls.size();i  ){
    k=webClientBuilder.
      build.get().
      uri(urls.get(i)).retrieve().
      bodyToFlux(String.class);
}

CodePudding user response:

There are a few issues with the code snippet you have provided so I would advise you firstly to have a read through the project reactor reference documentation

The code snippet below will hopefully achieve what you are looking for. Though if the desire is to run this as part of a reactive pipeline, you will want to return the Flux from this method instead of subscribing. The underlying framework (spring boot in this case) will initiate the subscription.

        List<String> urls = Arrays.asList("https://google.com", "https://yahoo.com");
        WebClient webClient = WebClient.builder().build();

        Flux.fromStream(urls.stream())
                .flatMap(url -> webClient.get()
                        .uri(url)
                        .retrieve()
                        .bodyToMono(String.class))
                .doOnNext(s -> System.out.println("Response: "   s))
                .subscribe();
  • Related