Java MongoDB POST:415不支持的mediatype [英] Java MongoDB POST : 415 unsupported mediatype
问题描述
我正在构建我的第一个API。 GET请求有效,但我遇到错误415不支持的mediatype的POST请求。经过一些搜索和重写代码后,它仍然失败。有人明白为什么吗?参数值为:
I am building my first API. The GET request works, but i am stuck at a POST request with error 415 Unsupported mediatype. After some searching and rewriting code, it still fails. Does someone see why? The parameter values are :
-String userName
-String password
-String phone
-String email
-List roles
代码:
UserResource:
CODE: UserResource:
@RolesAllowed("OWNER")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void create(@PathParam( "userName" ) String userName,@PathParam( "password" ) String password,@PathParam( "phone" ) String phone,@PathParam( "email" ) String email,@PathParam( "roles" ) List<String> roles)
{
User user = new User();
user.setName(userName);
user.setPassword(password);
user.setPhone(phone);
user.setEmail(email);
user.setRoles(roles);
userService.createUser(user);
}
UserService:
UserService:
public void createUser(User user){
userDAO.create(user);
}
UserDAO:
public void create( User user )
{
save( user );
}
POST请求:
localhost:8080/User/?userName=Daniel&password=test&phone=0634554567&email=daniel@email.com&roles=["OWNER"]
推荐答案
您有两个问题:
- 省略
@Consumes(MediaType.APPLICATION_JSON)
。您的请求与json没有任何关系。 -
@PathParam
s应替换为@RequestParam
s。这些值将作为请求参数(查询字符串)读取,而不是作为路径部分读取。
- Omit
@Consumes(MediaType.APPLICATION_JSON)
. Your request has nothing whatsoever to do with json. @PathParam
s should be replaced with@RequestParam
s. The values are read as request parameters (query string) and not as path parts.
此外,在请求示例中,您应该摆脱额外的 /
在用户
之后:
Also, in the request example you should get rid of the extra /
after User
:
localhost:8080 / User?userName = Daniel& ...
为了使用路径参数,您应该在资源方法配置中添加路径注释,例如:
In order to use path parameters, you should add a path annotation to the resource method configuration, something such as:
@RequestMapping(/ {userName} / {password} / {phone} / {email} / {roles}
并且请求应如下所示:
localhost:8080 / User / Daniel / test / 0634554567 / daniel / OWNER
这根本不直观
最后一件事: List< String> roles
是错误的。无论你使用路径还是查询参数,Spring都不会转换为字符串列表。你将拥有自己将角色分成数组(可能使用,
作为分隔符)或提供转换器
。
And one last thing: List<String> roles
is wrong. Spring won't convert to a list of strings, no matter if you use path or query parameter. You will have to split the roles into array yourself (probably using ,
as a separator) or supply a Converter
.
这篇关于Java MongoDB POST:415不支持的mediatype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!