You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot接口ResponseEntity无输出:Curl/Postman无响应问题

问题解决:Spring Boot异步POST接口无返回输出

问题根源

你的POST接口使用了@Async注解,但返回类型是ResponseEntity<String>——异步方法必须返回Future或其子类,否则Spring MVC无法正确处理异步响应的回调流程,导致客户端(curl)一直等待却收不到返回内容,尽管后端代码执行完全正常。

解决方案

1. 修改接口返回类型为CompletableFuture<ResponseEntity<String>>

调整后的代码如下:

@PostMapping
@Async
public CompletableFuture<ResponseEntity<String>> postMessage(@RequestBody Messages message ){
    if(message.getUserName() == null || message.getTextMessage() == null){
        System.out.println("No Username or TextMessage");
        return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
    }
    if(message.getTimeOut() !=null && message.getTimeOut() < 0){
        return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
    }
    String id = UUID.randomUUID().toString();
    message.setTextId(id);
    if(message.getTimeOut() == null) {
        message.setTimeOut(60);
        message.setTimeOutDate(60*1000+System.currentTimeMillis());
    }
    else{
        message.setTimeOutDate(message.getTimeOut()*1000+System.currentTimeMillis());
    }
    System.out.println("Attempting save");
    messagesRepository.save(message);
    return CompletableFuture.completedFuture(new ResponseEntity<>("id: "+id, HttpStatus.CREATED));
}

2. 确保项目启用异步支持

在Spring Boot启动类上添加@EnableAsync注解,开启异步功能:

@SpringBootApplication
@EnableAsync
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

3. 重新测试curl请求

再次执行你的POST curl命令,此时应该能正常收到返回的id: xxx内容。

原理说明

当方法标记@Async后,Spring会将该方法的执行提交到异步线程池,若返回普通类型,Spring无法跟踪异步任务的完成状态,也就无法在任务结束后将响应发送给客户端。返回CompletableFuture(或Future)后,Spring MVC会等待异步任务完成,再将结果封装成HTTP响应返回给客户端。

内容的提问来源于stack exchange,提问作者Geogrio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 01:11:32