How to get body from a request?

1k Views Asked by At

I'm using play 2.8.x framework as a backend and I need to get POST requests from clients. These requests have a JSON body like the following:

{
  "userId": "jjjjssss"
}

and I want to have the Controller method on the server-side looks like the following:

public Result getUser(String userId) {
   ...
   return ok();
}

or something like this:

public Result getUser(String jsonBody) {
   ...
   return ok();
}

How can I do it?
Can the play 2.8.x framework pass the body of requests to the controller method?

1

There are 1 best solutions below

3
VM4 On BEST ANSWER

Well if I understand what you're asking correctly you have to parse the request body in the controller method like this:

YourJsonClass theBody = request.body().parseJson(YourJsonClass.class)

This way the userId will have to be in YourJsonClass and the url path would be redundant.

More on this here: https://www.playframework.com/documentation/2.8.x/JavaJsonActions#Handling-a-JSON-request

Just make sure that your request is a POST request that has the Content-Type header set to

application/json;charset=utf-8