Reputation: 1927
I'm using play framework in Java. I want to retrieve the entire request body sent in a POST request to the play server. How can I retrieve it?
Upvotes: 14
Views: 18831
Reputation: 154
It will give request JSON body as string. I tested it on play 2.6.x
val body = request.body.asJson.get.toString()
Upvotes: 0
Reputation: 575
If you call the following code on a request;
String bodyText = request().body().asText();
bodyText will be null if the Content-Type header is application/json
There isn't a way using the provided controller APIs to just get JSON text if the Content-Type header is application/json without first converting to a JsonNode
So the best way to do this if the application/json is your Content-Type header is
String bodyText = request().body().asJSON().toString();
This is a fail on play framework's part, because they should just have a method to get the request body as a String no matter what the Content-Type header is.
Upvotes: 4
Reputation: 698
With Play Framework 2.3 it is possible to get raw json text even is Content-Type header is application/json
def postMethod = Action(parse.tolerantText) { request =>
val txt = request.body
}
Upvotes: 13
Reputation: 55798
Take a look into play.mvc.Http
class, you have some options there (depending on data format) i.e.
RequestBody body = request().body();
MultipartFormData formData = request().body().asMultipartFormData();
Map<String, String[]> params = request().body().asFormUrlEncoded();
JsonNode json = request().body().asJson();
String bodyText = request().body().asText();
You can test request().body().asText()
i.e. using cUrl from commandline:
curl -H "Content-Type: text/plain" -d 'Hello world !' http://domain.com/your-post-action
... or using some tool, like browser plugin: https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo
Upvotes: 15