所以我有一个简单的 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/