简体   繁体   English

Spring Webflux WebClient

[英]Spring Webflux WebClient

I don't really know how to translate the following call to the spring webflux webclient correctly.我真的不知道如何正确地将以下调用转换为 spring webflux webclient。

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. userIds 是列表,我能够使用以下语法调用该服务,但我无法使用 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:这是我将其转换为 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);

You should not change your list to flux, you should send it as list like this您不应该将您的列表更改为flux,您应该将其作为这样的列表发送

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这段代码没有经过测试,但原理是一样的

使用.bodyValue(userIds).syncBody(userIds) (已弃用)代替 body 插入器

**you can refer below mentioned code snippets ** **你可以参考下面提到的代码片段**

WebClient.post().uri(endPointUrl)
           .contentType(MediaType.APPLICATION_XML)
          .body(Mono.just(xmlEntity), String.class)
          .retrieve()
@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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM