1

I have a code which gets a body POST from Postman:

@RequestMapping(value="/dep", method=RequestMethod.POST)
public JsonResponse dep(@RequestBody String body) throws SQLException {

    Connection connection = ConnectionSingleton.getInstance().getConnection(env);

    Statement statement = connection.createStatement();

    statement.close();
    connection.close();
    System.out.println("BODY #### "+body);
    return new JsonResponse("depreciated");
}

Postman sent:

{
    "idn":"MLCM00292",
    "monto":"9149.92"
}

And the string is like:

%7B%0A%09%22idn%22%3A%22MLCM00292%22%2C%0A%09%22monto%22%3A%229149.92%22%0A%7D=

The words in bold are the parameters and their assigned values. I want to receive the parameters like variable. What its the correct way to get the params from a body in a POST request? What is missing in my code?

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
FranzSif
  • 113
  • 2
  • 11

1 Answers1

2

You can use a Map like this:

public JsonResponse dep(@RequestBody Map<String, String> body)

and then inside the method get the values like this:

String id = body.get("idn");
String monto = body.get("monto");

You can change the generics type for the Map class as it fits your needs. For example, if you are going to receive values of different types you can use it like Map<String, Object> body, then you could parse every value according to the data type (which you must know in advance). Something like:

String id = body.get("idn").toString();
double monto = Double.parseDouble(body.get("monto").toString());

For more complex data type I recommend you to create some custom POJOs or JavaBeans.

Further readings

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • 1
    I get the next json `{ "timestamp": "2018-10-24T15:12:26.847+0000", "status": 415, "error": "Unsupported Media Type", "message": "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported", "path": "/irs/depreciation" }` the message is `Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported` – FranzSif Oct 24 '18 at 15:15
  • `Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported` – FranzSif Oct 24 '18 at 15:16
  • @FranzSif Do you need to send the info as `application/x-www-form-urlencoded`? If not, you can send it as JSON by setting in the _Postman_ request > `Body` > `raw` > `JSON (application/json)` option. – lealceldeiro Oct 24 '18 at 15:20
  • @FranzSif Or you could try setting to the `@RequestMapping` the value `consumes = APPLICATION_FORM_URLENCODED_VALUE` – lealceldeiro Oct 24 '18 at 15:22