0

I'm calling an external API via WebClient to create a resource. But getting WebClientResponseException$BadRequest while testing from Postman. Here are few things I've tried without success:

  1. Building URI path from uribuilder
  2. Coverting entity to MultiValueMap before inserting into the request

Controller:

    @PostMapping("/createMessage")
    public String createMessage(@RequestBody Message request) {
        return service.createMessage(request);
    }

Service:

   public String createMessage(Message requestBody) { 
        ObjectMapper mapper = new ObjectMapper();
        MultiValueMap requestBodyForm = new LinkedMultiValueMap<String, Object>();
        Map<String, Object> requestBodyMap = mapper.convertValue(requestBody, new TypeReference<Map<String, Object>>() {});
        requestBodyForm.setAll(requestBodyMap);

        String id =  webClient.post()
                                .uri(properties.getMessageUrl())
                                .contentType(MediaType.APPLICATION_JSON)
                                .headers( headers -> 
                                            headers.setBasicAuth(user,pass))
                                .body(BodyInserters.fromValue(requestBodyForm))
                                .retrieve()
                                .bodyToMono(String.class)
                                .block();
        return id;
    }

Any direction where might be the problem would help a lot.

The external service is an IoT device controller API, with predefined message format:

$ curl --location --request POST 'http://external-service/message' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic xxxxxxxxxxxx' \
--data-raw '[{
"message": "Testing service reachability",
"defaulttext": "This is Message Zone",
"startDate": "2021-05-25 15:20:00",
"duration":10,
...
}]'

198                                                         
Deepak D
  • 148
  • 11
  • 1
    Would be good if you could include the api description – Toerktumlare Sep 23 '21 at 16:46
  • 1
    It's probably the body of the request is badly formatted. you should look at the returned value from BodyInserters.fromValue(requestBodyForm) – Francis Robitaille Sep 23 '21 at 21:49
  • @francis-robitaille, thanks, you're right. It needs to be `BodyInserters.fromFormData(requestBodyForm)`, but I'm getting `UnsupportedMediaType` error. Tried so many permutations without success. I feel like understanding the rationale behind these constructs better, a good documentation (not Baeldung how-to's) with ample examples would be nice to study. – Deepak D Sep 24 '21 at 12:28

0 Answers0