Java MongoDB POST : 415 unsupported mediatype

扶醉桌前 提交于 2019-12-12 04:34:24

问题


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

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:

public void createUser(User user){
userDAO.create(user);
}

UserDAO:

public void create( User user )
{
    save( user );
}

the POST request:

localhost:8080/User/?userName=Daniel&password=test&phone=0634554567&email=daniel@email.com&roles=["OWNER"]

回答1:


You have two issues:

  1. Omit @Consumes(MediaType.APPLICATION_JSON). Your request has nothing whatsoever to do with json.
  2. @PathParams should be replaced with @RequestParams. 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}

and the request should look something such as:

localhost:8080/User/Daniel/test/0634554567/daniel/OWNER

Which is not intuitive at all

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.



来源:https://stackoverflow.com/questions/40218320/java-mongodb-post-415-unsupported-mediatype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!