pullCommitRun
pullCommitRun

Reputation: 383

Reading the contents of a body of a POST request in java (using REST)

Suppose I make a POST request using POSTMAN and have a body in json format. I want to read the contents of body and pass it in a method. How to do it ?

I can see that there is @QueryParam, @PathParam, @HeaderParam etc annotation are used to read the parameters. I don't get how to read body.

say body is
{ "param1":"value1", "param2":"value2", "param3":"value3", }

ServerSide java code:

@POST

@Path("/myresource")

public Response addParams( String param1, String param2, String param3) { do somthing. }

So I wanted this param1,param2,parmam3 values to be read from requestbody. Is it possible ?

Upvotes: 0

Views: 5451

Answers (2)

cassiomolin
cassiomolin

Reputation: 131117

Define a class like:

public class Foo {

    String param1;
    String param2;
    String param3;

    // Default constructor, getters and setters
}

Then use it as follows:

@POST
@Path("/myresource")
@Consumes(MediaType.APPLICATION_JSON)
public Response addParams(Foo params) {

    String param1 = params.getParam1();
    String param2 = params.getParam2();
    String param3 = params.getParam3();

    ...
}

Alternatively, use a Map<String, String>:

@POST
@Path("/myresource")
@Consumes(MediaType.APPLICATION_JSON)
public Response addParams(Map<String, String> params) {

    String param1 = params.get("param1");
    String param2 = params.get("param2");
    String param3 = params.get("param3");

    ...
}

Just ensure that you have a JSON parser such as Jackson or MOXy configured in your application.

Upvotes: 1

dZ.
dZ.

Reputation: 404

Don't know which Java framework you use, but you could declare a @RequestBody parameter in your method and "map" it to a POJO that will correspond to the incoming JSON (just like @Smutje said in the comment).

For example, in Spring, we do it like this,

@PostMapping(value = "/example",
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
 public ResponseEntity postExample(@RequestBody ExamplePOJO examplePOJO) {

 // Do something
}

Upvotes: 0

Related Questions