1

我希望在我的代码中模仿以下发布请求:

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”,“标识符”:“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。

4

1 回答 1

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(); 
于 2019-10-10T07:01:56.593 回答