gpt4 book ai didi

rest - 在 REST 中测试 POST 请求

转载 作者:行者123 更新时间:2023-11-28 20:23:51 24 4
gpt4 key购买 nike

我正在使用 Postman(chrome 扩展)来测试这个 REST 服务,我能够成功地测试 GET 和 DELETE:http://localhost:8080/mt-rest/rest/user/321,但不是 POST,即使在提供表单数据之后也是如此。我明白了。服务器拒绝了这个请求,因为请求实体的格式不受所请求方法的请求资源的支持。我在这里做错了什么?

enter image description here

@Controller
@RequestMapping("rest")
public class TestController {![enter image description here][2]

@Autowired
private MultitenantService service;

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
@ResponseBody
public User getUserInfo(@PathVariable Long id) {
return service.getUser(id);
}

@RequestMapping(value = "/user", method = RequestMethod.GET)
@ResponseBody
public List<User> getCustomers() {
return service.getUsers();
}

@RequestMapping(value = "/user/{id}/todo", method = RequestMethod.GET)
@ResponseBody
public List<TodoItem> getTransactions(@PathVariable Long id) {
return getUserInfo(id).getTodoItems();
}

@RequestMapping(value = "/user/{id}/todo", method = RequestMethod.POST)
@ResponseBody
public List<TodoItem> addTransaction(@PathVariable Long id, @RequestBody TodoItem todoItem) {

User user = getUserInfo(id);
user.getTodoItems().add(todoItem);

service.save(user);

return user.getTodoItems();
}

@RequestMapping(value = "/user/{id}/todo/{todoId}", method = RequestMethod.DELETE)
@ResponseBody
public User addTransaction(@PathVariable Long id, @PathVariable Long todoId) {

User user = getUserInfo(id);

user.deleteTodo(todoId);

service.save(user);

return getUserInfo(id);
}
}

更新:

在我的 POST 方法中,我从 @RequestBody 更改为 @ModelAttribute,现在我得到了

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ConstraintViolationException: Validation failed for classes [net.tajzich.mt.domain.TodoItem] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=name, rootBeanClass=class net.tajzich.mt.domain.TodoItem, messageTemplate='{javax.validation.constraints.NotNull.message}'}

]

最佳答案

这对我有用,我没有正确设置页眉。-H "Content-Type: application/json"

$ curl -i -X POST -d '{"version":"1","name":"Himalay","done":"false"} ' http://localhost:8080/mt-rest/rest/user/2/todo -H "Content-Type: application/json"

HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: application/json Transfer-Encoding: chunked Date: Thu, 23 Jan 2014 22:17:34 GMT

============================================= =========================

关于rest - 在 REST 中测试 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21315167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com