2014-01-23 86 views
1

我正在使用Postman(chrome扩展)来测试此REST服务,并且我能够成功测试GET和DELETE:http://localhost:8080/mt-rest/rest/user/321,但不支持POST,即使在提供表单数据之后。 我得到..服务器拒绝了这个请求,因为请求实体的格式不是所请求方法的请求资源所支持的格式。我在这里做错了什么?在REST中测试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}'} 

]

+0

不要过多细节,但我认为你的POST方法'@RequestMapping(value =“/ user/{id}/todo”'是错误定义的。您没有请求任何内容,但是您正在向Web服务提交。 – Sid

回答

3

这为m工作e,我没有正确设置标题。 -H “内容类型:应用程序/ 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服务器:Apache-狼/ 1.1 Content-Type的: 应用/ JSON传输编码:分块日期:星期四,2014年1月23日 22时十七分34秒GMT

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