英文:
Why this code can't POST anything using Rest API?
问题
这段代码为什么无法工作你看得明白吗?我无法通过addTopic函数将任何主题添加到我的列表中(我在末尾附上了错误消息)。
private List<Topic> topics = new ArrayList<>(Arrays.asList(
new Topic("java", "back", "java description"),
new Topic("html", "front", "html description")
));
public void addTopic(Topic topic) {
topics.add(topic);
}
@PostMapping("/topics")
public void addTopic(@RequestBody Topic topic) {
topicService.addTopic(topic);
}
public class Topic {
private String id;
private String name;
private String description;
public Topic(String id, String name, String description) {
super();
this.id = id;
this.name = name;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
英文:
Do you see why this code doesn't work? I can't add any topic to my list through function addTopic (I get a error message attached at the end).
private List<Topic> topics = new ArrayList<>(Arrays.asList(
new Topic("java", "back", "java description"),
new Topic("html", "front", "html description"),
));
public void addTopic(Topic topic) {
topics.add(topic);
}
@PostMapping("/topics")
public void addTopic(@RequestBody Topic topic) {
topicService.addTopic(topic);
}
public class Topic {
private String id;
private String name;
private String description;
public Topic(String id, String name, String description) {
super();
this.id = id;
this.name = name;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
答案1
得分: 0
@PostMapping(path = "/**", consumes = "application/json", produces = "application/json")
public void addTopic(@RequestBody Topic topic) {
//code
}
英文:
@PostMapping(path = "/***", consumes = "application/json", produces = "application/json")
public void addTopic(@RequestBody Topic topic) {
//code
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论