Grails使用RestBuilder调用含对象参数端点返回404如何解决?
问题根因
你遇到的404问题90%以上是Grails框架的默认行为导致:当Controller的Action接收命令对象(Command Object)作为参数时,如果参数绑定失败/校验不通过,框架会直接返回404状态码,不会进入Action方法执行逻辑。除此之外路由配置错误、请求方式不匹配也可能导致该问题。
具体解决步骤
1. 修正请求代码
你当前手动拼接JSON字符串再转字节流的写法容易出错,RestBuilder支持直接传入Map自动序列化,调整后的代码如下:
RestResponse restResponse; // 直接用Map定义参数,避免JSON格式错误 def parameters = [qtdThreads:3, channel:"http://localhost:8081/application2"] try { restResponse = new RestBuilder().post("http://localhost:8080/application/endPoint") { accept("application/json") contentType "application/json; charset=utf-8" // 直接传入Map,框架会自动按contentType序列化为JSON body parameters connectTimeout 1000 } } catch (Exception e) { e.printStackTrace(); } finally { return restResponse; }
2. 修正目标端点配置
需要明确指定Action接收POST请求,同时添加@RequestBody注解告诉Grails从请求体中读取JSON绑定到命令对象:
import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import grails.web.http.HttpStatus @PostMapping("/endPoint") Object endPoint(@RequestBody ObjectCommand command) { render(status: HttpStatus.OK) }
如果你的Controller没有配置根路径,需要在类上添加@RequestMapping("/application")注解保证路径匹配。
3. 可选优化命令对象配置
给命令对象添加@CommandObject注解,明确标记为绑定用的命令对象,避免低版本Grails识别异常:
import grails.validation.Validateable import grails.web.databinding.CommandObject @CommandObject @Validateable class ObjectCommand { URL channel Integer qtdThreads static constraints = { qtdThreads(validator: { Integer val -> if (!val || val <= 0) { return "message1" } }) channel(validator: { URL val -> if (!val) { return "message2" } }) } }
4. 验证排查
如果修改后依然返回404,按以下步骤定位:
- 先临时删除Action的
ObjectCommand command参数,发起请求如果返回200,确认是绑定问题,可开启Grails的绑定日志查看具体失败原因 - 检查
UrlMappings.groovy中是否有和/application/endPoint冲突的路由配置 - 用Postman直接发起请求测试,排除跨域预检请求被拦截的问题
- 检查是否有全局拦截器/过滤器拦截了该路径的请求
内容的提问来源于stack exchange,提问作者Joao G. Hartmann
相关产品推荐
相关产品推荐

