tsure
tsure

Reputation: 315

POST request to Spring REST web service fails with HTTP status 415

I have set up a spring RESTful web service for taking in the username and password from a user. Been following the tutorial on Spring IO

My service is set up to accept user name and password as shown below:

 @Controller
   @RequestMapping("/users")
   public class UserCommandController {
        private static Logger log = LoggerFactory.getLogger(UserCommandController.class);
        @RequestMapping(method = RequestMethod.POST)
        public ResponseEntity  createUser(@RequestBody UserDetail userDetail, UriComponentsBuilder builder) {
            User newUser = new User();
            newUser.setEmail(userDetail.getEmail());
            newUser.setPassword(userDetail.getPassword());
            newUser.setUserName(userDetail.getUsername());
            try {
                UserFactory.getInstance().saveNewUser(newUser);
            } catch(UserException ue) {
                log.error("Saving user failed. Exception: "+ue.getMessage());
            }
            return new ResponseEntity(HttpStatus.OK);
        }
    }

I am sending POST parameters to the service as a test through Google chrome plugin POSTMAN but I get "HTTP: 415..The server refused this request because the request entity is in a format not supported by the requested resource for the requested method."

enter image description here

Does anyone have an idea what I am doing wrong ?

Upvotes: 1

Views: 14393

Answers (2)

dhrubo
dhrubo

Reputation: 179

Set the header:

Content-Type=application/json

This solved my problem!

Upvotes: 1

EJK
EJK

Reputation: 12527

The HTTP 415 response code means that the server expected data posted with a different content type. It appears you simply posted a form with username, password and email as parameters. That would result in a content-type of application/x-www-form-urlencoded.

Try posting with a content-type of application/xml or application/json. In your post body, you will need to put your data in the corresponding format. For example, if you use application.xml, the XML body should look something like:

<userDetail>
    <userName>xxx</userName>
    <password>xxx</password>
    <email>xxx</email>
</userDatail>

Of course the exact format (i.e. element names) depends on the XML bindings. In fact, whether or not the expected format is XML or JSON or something else is also likely a server configuration.

Posting a request of this type cannot easily be done with a browser. You will need some other HTTP client. A tool like SOAP-UI might be a good bet.

Upvotes: 0

Related Questions