Rest Service 看不到来自 Grails Rest Client Builder 的参数

标签 rest grails

所以我有一个简单的 Grails UI,它在一个表单中包含几个字段 .. firstName、lastName 等。 Controller 调用服务方法,然后使用 Rest Client Builder 插件调用 REST 服务。

但是,其余服务无法识别参数。

这是简单的休息电话。

    def resp = rest.post(baseUrl, params)
            {
                header 'Accept', 'application/json'
                contentType "application/x-www-form-urlencoded"
            }

使用插件的 2.0.1 版本。

参数看起来像
[firstName:Kas, action:index, format:null, controller:myController, max:10]

休息服务方法看起来像......
@POST
@Path("/employees")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
public IdmResult createNewEmployee(@FormParam("firstName") String firstName) {
    try {
        if(firstName == null) return constructFailedIdmResult("First Name is a required field");

        // Do some other stuff
    }
 }

服务响应“名字是必填字段”

当我从 postman 提交帖子时,它工作正常。 postman 的成功请求看起来像
POST /idm/employees HTTP/1.1
Host: <ip>:<url>
Accept: application/json 
firstName: Kas
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded

想知道如何查看插件正在构建的请求,以便比较差异,但最终我只需要知道如何正确地从插件发送请求,以便 Rest Service 识别表单参数。

最佳答案

休息客户端应该使用请求正文来发布:

def resp = rest.post(baseUrl) {
    header 'Accept', 'application/json'
    contentType "application/x-www-form-urlencoded"
    json {
        firstName = "Kas"
    }
}

或者简单地说,
def resp = rest.post(baseUrl) {
    header 'Accept', 'application/json'
    contentType "application/x-www-form-urlencoded"
    json firstName: "Kas"
}

引用 docs详情。

更新:

由于生产者期望请求参数是大查询字符串而不是 JSON,因此您最终可能会这样做:
def queryString = params.collect { k, v -> "$k=$v" }.join(/&/)

def resp = rest.post("$baseUrl?$queryString") {
    header 'Accept', 'application/json'
    contentType "application/x-www-form-urlencoded"
}

或只是 def resp = rest.post("$baseUrl?$queryString")

关于Rest Service 看不到来自 Grails Rest Client Builder 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22415689/

相关文章:

Grails:设置 NUMBER 列的长度?

grails - 从简单的HTTP位置重新安装grails插件

rest - Camel ReSTLet maxThreads 组件选项

JavaEE6+REST : How do I get all REST resources at runtime?

java - 实现 RESTful Web 服务

grails - 在NB上运行时出现Grails错误

rest - 在 Grails 中持续轮询 REST 服务

json - 如何形成 ASP.NET OData WebApi 的 PATCH 正文?

javascript - gsp更改未反射(reflect)在grails 2.5.1中

testing - Grails 集成测试因 MissingMethodException 而失败