Home > other >  Using BodyInserters to pass parameter with webClient
Using BodyInserters to pass parameter with webClient

Time:11-18

There is my code.

public Mono<RespDto> function(TransReqDto1 reqDto1, TransReqDto2 reqDto2, String token) {

    MultipartBodyBuilder builder = new MultipartBodyBuilder();
    builder.part("TransReqDto1", reqDto1);
    builder.part("TransReqDto2", reqDto2);

    MultiValueMap<String, HttpEntity<?>> parts = builder.build();

    LinkedMultiValueMap map = new LinkedMultiValueMap();
    map.add("TransReqDto1", reqDto1);
    map.add("TransReqDto2", reqDto2);

    return
            client.post()
                    .uri("/api")
                    .body(BodyInserters.fromValue(reqDto1))
                    .headers(h -> h.setBearerAuth(token.split(" ")[1]))
                    .retrieve()
                    .bodyToMono(RespDto.class);
       
}

My probelm is that I need to send both reqDto1 & reqDto2. I've successfully sent reqDto1 with the code above but I can't figure out a way to send two objects. Tried MultipartBodybuild and MultiValueMap but both are returning error from the target API. Please give me some hints!! Thank you

Here is the API I am trying to call!

@PostMapping("")
@ApiOperation(value = "test", notes = "test")
public Mono<?> transPost(@Valid @RequestBody TransReqDto1 reqDto1,
                         @Valid @RequestBody TransReqDto2 reqDto2) {
    return testService.function(reqDto1, reqDto2);
}

CodePudding user response:

You cannot use two @RequestBody. It can bind to a single object only. The expected way to do that is to create a wrapper DTO containing all the relevant data:

public class TransReqDto {

  private TransReqDto1 transReqDto1;
  private TransReqDto2 transReqDto2;
//...
}
  • Related