Retrieve the request body string sent in POST request in play framework java

17,420

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.

Share:
17,420
Bourne
Author by

Bourne

Updated on June 07, 2022

Comments

  • Bourne
    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
    Bourne about 10 years
    I want to get the raw body string without converting it to any java specific data structures. How can I achieve this?
  • biesior
    biesior about 10 years
    You should look into mentioned class :P String bodyText = request().body().asText();
  • Bourne
    Bourne about 10 years
    I have tried String bodyText = request().body().asText(); . It returns null :)
  • biesior
    biesior about 10 years
    Aparently 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
    Gerhard Hagerer over 7 years
    Probably that would help then: ricardclau.com/2015/06/…