Reputation: 969
So I have a simple Grails UI which takes a few fields .. firstName, lastName etc. in a form. The controller calls a service method which then uses the Rest Client Builder plugin to call a REST service.
The rest service is not recognizing the parameters however.
Here is the simple rest call.
def resp = rest.post(baseUrl, params)
{
header 'Accept', 'application/json'
contentType "application/x-www-form-urlencoded"
}
Using version 2.0.1 of the plugin.
params looks like
[firstName:Kas, action:index, format:null, controller:myController, max:10]
Rest Service Method looks like ...
@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
}
}
Service responds with "First Name is a required field"
When I submit the Post from Postman it works fine. Successful request from Postman looks like
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
Would like to figure how I can see the request that the plugin is constructing so I can compare differences, but ultimately I just need to know how to properly send the request from the plugin so that the Rest Service recognizes the form parameters.
Upvotes: 1
Views: 3513
Reputation: 29837
To pass the values cleanly in the request body, use a MultiValueMap and the (undocumented, from what I see) 'body()' method as per this answer. https://stackoverflow.com/a/21744515/17123
Upvotes: 2
Reputation: 50245
Rest client should be using request body to POST:
def resp = rest.post(baseUrl) {
header 'Accept', 'application/json'
contentType "application/x-www-form-urlencoded"
json {
firstName = "Kas"
}
}
or simply,
def resp = rest.post(baseUrl) {
header 'Accept', 'application/json'
contentType "application/x-www-form-urlencoded"
json firstName: "Kas"
}
Refer docs for detail.
UPDATE:
Since producer is expecting request params as big query string instead of JSON, you might end up doing this instead:
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"
}
or just def resp = rest.post("$baseUrl?$queryString")
Upvotes: 4