Retrieve the request body string sent in POST request in play framework java
Solution 1
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
Solution 2
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
}
Solution 3
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.
Bourne
Updated on June 07, 2022Comments
-
Bourne almost 2 years
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?
-
Bourne about 10 yearsI want to get the raw body string without converting it to any java specific data structures. How can I achieve this?
-
biesior about 10 yearsYou should look into mentioned class :P
String bodyText = request().body().asText();
-
Bourne about 10 yearsI have tried String bodyText = request().body().asText(); . It returns null :)
-
biesior about 10 yearsAparently your post contains i.e. form instead of plain text, try to perform call to the action - ie using Play's WS API or curl to see it works ;)
-
Gerhard Hagerer over 7 yearsProbably that would help then: ricardclau.com/2015/06/…