【问题标题】:POST Request in WebClient in Spring Boot and Receive responce as JSONObjectSpring Boot 中 WebClient 中的 POST 请求并作为 JSONObject 接收响应
【发布时间】:2026-02-13 10:45:02
【问题描述】:

我正在尝试在 Spring Boot 中使用 WebClient 发出 API POST 请求。但我不能以 JSONObject 的形式发出请求并接收响应。用RestTemplate我做到了,最近我开始学习WebClient。以至于我被卡住了。

错误 Spring 给出: 错误:(48, 28) java: 不兼容的类型:不存在类型变量 T 的实例,因此 reactor.core.publisher.Mono 符合 org.json.simple.JSONObject

这是我的源代码:

Controller.java

        JSONObject jsonObject = new JSONObject();
        Turnover turnover = new Turnover();

               JSONObject resp = webClientBuilder.build()
                .post()
                .uri("http://180.12.10.10:8080/turnover/")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .accept(MediaType.APPLICATION_JSON )
                .body(Mono.just(turnover),Turnover.class)
                .retrieve()
                .bodyToMono(JSONObject.class);

Turnover.java


@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor

public class Turnover {

    private String start_date;
    private String end_date;
    private String account;

    public Turnover(){
        setStart_date("01.01.2020");
        setEnd_date("01.06.2020");
        setAccount("20296");
    }
}

我要发送的 Json

{
  "start_date":"01.01.2020",
  "end_date":"01.06.2020",
  "account":"20296"
}

响应 API 返回:

{
    "status": 1,
    "message": "success",
    "data": [
        {
            "CODE_ACCOUNT": "20296",
            "CREDIT": 60610187386.86,
            "DEBIT": 60778253872.1
        }
    ]
}

任何帮助表示赞赏!

【问题讨论】:

  • 发布完整的堆栈跟踪。

标签: java spring-boot webclient


【解决方案1】:

最有可能的问题是您要求返回一个字符串,但将其分配给 JSONObject。这个异常看起来很奇怪,我希望你所拥有的会出现编译错误,但试试这个:

  .bodyToMono(JSONObject.class)
  .block();

您需要将请求中的内容类型修复为MediaType.APPLICATION_JSON ,以便它将您的对象作为 json 传递。

【讨论】:

  • 它没有用。错误org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/x-www-form-urlencoded' not supported for bodyType=com.genericspringproject.genericspringpro.model.Turnover
  • @Abdusoli 添加了缺失的行。您需要 .block(); 来获取实际类型。否则它会返回 Mono<JSONObject> 给你,因为它是响应式的。
  • 现在添加block() 后也会出现上述错误
  • 这是不正确的:我假设.contentType(MediaType.APPLICATION_FORM_URLENCODED) 应该是MediaType.APPLICATION_JSON
  • 是的,兄弟,现在一切正常。如果你正确地更新你的答案,那么我会收到它作为正确答案
最近更新 更多