向外部API发送发布请求并提取数据

时间:2019-10-10 06:43:41

标签: spring-boot java-8 spring-webclient

我希望在我的代码中模仿以下帖子请求:

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

理想情况下,我得到的JSON响应会是这样

  

{     “数据”:{       “ id”:“ 111”,       “ identifier”:“ test1”,       “秘密”:“秘密”     }   }

我正在尝试使用WebClient建立这样的请求

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(); 

我遇到了错误

  

org.springframework.web.reactive.function.client.WebClientResponseException $ BadRequest:400错误请求

执行此操作时...我要去哪里错了?还有发送这种请求的更有效的方法吗?我无法理解如何正确使用Mono。

1 个答案:

答案 0 :(得分:1)

创建实体类并将其作为对象发送

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();