Java MongoDB POST:415 不受支持的媒体类型 [英] Java MongoDB POST : 415 unsupported mediatype
问题描述
我正在构建我的第一个 API.GET 请求有效,但我被困在 POST 请求中,错误为 415 Unsupported mediatype.经过一些搜索和重写代码,它仍然失败.有人明白为什么吗?参数值为:
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
代码:用户资源:
@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);
}
用户服务:
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.
此外,在请求示例中,您应该去掉 User
之后的额外 /
:
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
是错误的.无论您使用路径还是查询参数,Spring 都不会转换为字符串列表.您必须自己将角色拆分为数组(可能使用 ,
作为分隔符)或提供 Converter
.
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 不受支持的媒体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!