Mirco Lcl Mirco Lcl - 3 years ago 229
reST (reStructuredText) Question

Unable to send data to POST Service in Spring 4

I'm trying to write a simple HTTP REST service using Spring 4.

I'm having troubles sending data to a POST endpoint

@RequestMapping(value = "/onlyPost", produces = "application/json", method
= RequestMethod.POST)
public @ResponseBody ResponseEntity<?> createUser(@RequestParam("value1")
String param1, @RequestParam("value2") String param2) {

While trying to send data with Postman, I receive a 400 message (obviously the values are setted in the request's body)

"message": "Required String parameter 'value1' is not present",

What I have noticed is that the issue is somewhat related to the headers, because when I remove the postman's header (Content-Type: application/json) everything works fine.

I tried for more than one hour fixing this by myself with no results. Any hints?

Answer Source

@RequestParam is used to read a URL query parameter.


For instance, in the URL above, value1 and value2 are query parameters that you can read using that annotation.

But if you want to read a JSON request instead, you need to change the method to:

@RequestMapping(value = "/onlyPost", method = RequestMethod.POST, 
    consumes = "application/json")
public @ResponseBody ResponseEntity<?> createUser(@RequestBody User user) {

where User is a POJO holding the two fields:

public class User {
    private String value1;
    private String value2;

    // getters and setters...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download