Prachi Bhardwaj
Prachi Bhardwaj

Reputation: 99

Error while executing post request in spring mvc

While Executing the following post request in postman:

http://localhost:8080/FinalSmsApi/rest/requestSms/hello

with parameter username,password and phone . I am getting the following error :

HTTP Status 415: The server refused this request because the request entity is in a format not supported by the requested resource for the requested method

This is the controller:

@RestController
public class MainController1 {
    @RequestMapping(value = "/hello", method = POST, consumes = "application/json")
    public void Register(@RequestParam(value = "username") String username,
                         @RequestParam(value = "password") String password,
                         @RequestParam(value = "phone") String phone) {...}
}

Using Spring 4 version.

Upvotes: 2

Views: 1604

Answers (1)

Ali Dehghani
Ali Dehghani

Reputation: 48213

HTTP Status 415: The server refused this request...

This means that your endpoint is not able to process the passed Request Body. This error have two main reasons: either you did not specify what is the type of your request body or you passed an invalid data.

By Adding Content-Type header to your request headers, this problem would be solved:

Content-Type: application/json

And also, you're not capturing request body in your public void Register(..) method. If you're planning to go this way, it's better to drop the consumes attribute and pass all the parameters with Query Parameters, as you did.

The other approach is to define a resource class like:

public class User {
    private String username;
    private String password;
    private String phone;

    // getters and setters
}

Then change your controller to capture the request body, like following:

@RequestMapping(value = "/hello", method = POST, consumes = "application/json")
public void Register(@RequestBody User user) {...}

And finally, send a JSON representation along with your request:

curl -XPOST -H'Content-Type: application/json' --data '{"username": "", "password": "", "phone": ""}' http://localhost:8080/hello

Upvotes: 1

Related Questions