Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 585
Bourne Avatar asked Apr 12 '14 19:04

Bourne


People also ask

How do I get request body from post request?

To retrieve the body of the POST request sent to the handler, we'll use the @RequestBody annotation, and assign its value to a String. This takes the body of the request and neatly packs it into our fullName String. We've then returned this name back, with a greeting message.

What is a request body?

A request body is data sent by the client to your API. A response body is the data your API sends to the client. Your API almost always has to send a response body. But clients don't necessarily need to send request bodies all the time.


2 Answers

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
}
like image 111
Viktor Aseev Avatar answered Oct 04 '22 18:10

Viktor Aseev


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

like image 25
biesior Avatar answered Oct 04 '22 18:10

biesior