我正在尝试使用 JSON 对我正在运行的 Spring Boot 应用程序进行 POST 调用,每次进行 POST 调用时都会收到以下错误
Request method 'POST' not supported
这是我的 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
和 Answer
是 POJO
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;
}
}
我希望能够将 JSON 发布到我的 Controller ,然后接收返回的 JSON 消息。我怎样才能让它工作而不出现错误?我通过 SoapUI 发布到 http://localhost:8080/messages
最佳答案
这就是我的想法:
描述的类型不应该是String而不是int?
private int description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description= description;
}
您的帖子 json 应该是:(假设 id 是整数,描述是字符串)
{"id": 1, "descripion":"Test message"}
尝试像这样转动你的 Rest Controller :
@RestController
@RequestMapping("messages")
public class MessagesController {
@RequestMapping(method = RequestMethod.POST)
public Answer processMessage(@RequestBody Message message) throws Exception{
关于java - 让 JSON Post 在 Spring Boot 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37934850/