问题描述
我不知道我在这里做错了什么.我正在使用邮递员"应用程序向服务发送请求.该参数是一个非常简单的 POJO,如下所示.当我尝试发送请求时,我得到一个响应:服务器拒绝了这个请求,因为请求实体的格式不受所请求方法的请求资源支持"
I can't fiure out what I am doing wrong here. I am using the app "Postman" to send a request to a service. The parameter is a very simple POJO shown below. When I attempt to send the request I get a response: "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method"
用于请求的类:
public class LoginAttempt {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
控制器中的 API:
@RequestMapping(value="/validate", method=RequestMethod.POST, produces="application/json")
public boolean validateUser(@RequestBody LoginAttempt login) {
System.out.println("Login attempt for user " + login.getUserName() + login.getPassword());
return true;
}
推荐答案
FormHttpMessageConverter 用于 @RequestBody-annotated 参数,当内容类型为 application/x-www-form-urlencoded 时无法绑定目标类作为 @ModelAttribute 可以).因此你需要@ModelAttribute 而不是@RequestBody
FormHttpMessageConverter which is used for @RequestBody-annotated parameters when content type is application/x-www-form-urlencoded cannot bind target classes as @ModelAttribute can).Therefore you need @ModelAttribute instead of @RequestBody
或者像这样使用@ModelAttribute注解而不是@RequestBody
Either Use @ModelAttribute annotation instead of @RequestBody like this
public boolean validateUser(@ModelAttribute LoginAttempt login)
或者您可以创建一个单独的方法表单处理表单数据,使用适当的 headers 属性,如下所示:
or you can create a separate method form processing form data with the appropriate headers attribute like this:
@RequestMapping(value="/validate", method=RequestMethod.POST, headers = "content-type=application/x-www-form-urlencoded" produces="application/json")
这篇关于RequestMapping POST API 有问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!