Search code examples
spring-bootjava-8spring-webclient

sending a post request to an external API and extracting data


I wish to mimic the following post request in my code :

curl -v -H "Accept: application/json" \
        -H "Content-type: application/json" \
        -H "App-id: $APP_ID" \
        -H "Secret: $SECRET" \
        -X POST \
        -d "{ \
              \"data\": { \
                \"identifier\": \"test1\" \
              } \
            }" \
        https://www.sampleurl.com/createuser

Ideally the JSON response i would get would be like this

{ "data": { "id": "111", "identifier": "test1", "secret": "SECRET" } }

I am trying to use WebClient to build such a request

WebClient req = WebClient.builder().baseUrl("https://www.sampleurl.com").build();
        String data = "{" + "\n" + "\t" + "\"data\": { \n";
        data += "\t" + "\t" + "\"identifier\": \"" + username + "\"\n";
        data += "\t" + "}" + "\n" + "}";
        body.setIdentifier(username);
        String t = req.post().uri("/createuser")
                      .contentType(MediaType.APPLICATION_JSON)
                      .accept(MediaType.APPLICATION_JSON)
                      .header("App-id", APPID)
                      .header("Secret", SECRET)
                      .body(BodyInserters.fromPublisher(Mono.just(data), String.class))
                      .retrieve()
                      .bodyToMono(String.class)
                      .doOnNext(myString -> {System.out.println(myString);})
                      .block(); 

I am getting the error

org.springframework.web.reactive.function.client.WebClientResponseException$BadRequest: 400 Bad Request

on doing this... Where am I going wrong? Also is there a more efficient way of sending such a request? I am not able to understand how to use Mono properly.


Solution

  • Create the entity class and send that as an object

    class RequestPayloadData {
        private String identifier;
    
        //..getters and setters (or lombok annotation on the class)
    }
    
    class RequestPayload {
        private RequestPayloadData data;
    
        //..getters and setters (or lombok annotation on the class)
    }
    
    WebClient req = WebClient.builder().baseUrl("https://www.sampleurl.com").build();
    RequestPayload data = new RequestPayload();
    data.setData(new RequestPayloadData("test1"));
    
    String t = req.post().uri("/createuser")
                  .contentType(MediaType.APPLICATION_JSON)
                  .accept(MediaType.APPLICATION_JSON)
                  .header("App-id", APPID)
                  .header("Secret", SECRET)
                  .body(BodyInserters.fromPublisher(Mono.just(data), RequestPayload.class))
                  .retrieve()
                  .bodyToMono(String.class)
                  .doOnNext(myString -> {System.out.println(myString);})
                  .block();