user906153
user906153

Reputation: 1218

Getting JSON Post to work in Spring Boot

I'm trying to make a POST call with JSON to a Spring Boot app that I am running, and I keep getting the following error each time I make a POST call

Request method 'POST' not supported

Here is the basic layout of my controller,

@RestController
public class MessagesController {

    @RequestMapping(value = "/messages", method = RequestMethod.POST)
    public @ResponseBody Answer processMessage(@RequestBody Message message) throws Exception{
        System.out.println("HERE");

        Answer a = new Answer(5);

        return a;
    }

    @ExceptionHandler
    void handleException(Exception e, HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.CONFLICT.value());
    }
}

Message and Answer are POJOs

public class Message implements Serializable{
    private int id;
    private int description;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description= description;
    }
}

public class Answer implements Serializable{
    private int answer;

    public Answer(int answer){
        this.answer = answer;
    }

    public int getAnswer() {
        return answer;
    }

    public void setAnswer(int answer) {
        this.answer = answer;
    }
}

I'd like to be able to POST JSON to my controller, and then receive a JSON message back. How do I get this to work, without the error? I am posting to http://localhost:8080/messages through SoapUI

Upvotes: 0

Views: 7461

Answers (1)

Minh
Minh

Reputation: 424

So these is what i think:
The type of description should not be String instead of int?

private int description;
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description= description;
}

Your post json should be:(assume that id is integer and descripion is String)

{"id": 1, "descripion":"Test message"}

Try to turn your Rest controller like this:

@RestController
@RequestMapping("messages")
public class MessagesController {
    @RequestMapping(method = RequestMethod.POST)
    public Answer processMessage(@RequestBody Message message) throws Exception{

Upvotes: 1

Related Questions