简体   繁体   中英

Take JSON with @POST on Restful

I'm trying to take JSON values on POST method but I don't know how to do this.

This is the code that I have:

@POST
@Path("/contacts")
@Consumes({"application/json"})
public void addContact() {

    HttpSession session = request.getSession(true);

    UserPK user = new UserPK((String) session.getAttribute("username"));
    //dest = TAKE JSON VALUE

    dao.addContact(user, dest);
}

I'm sending the JSON value with firefox RestClient with this look:

{"param1":"value"}

How can I take this value?

We also have this error message: 415 Unsupported Media Type

Thanks.

Make sure you are actually sending a post and the content-type of your request is application/json. To consume this with spring MVC you can use the @RequestBody annotation:

@POST
@Path("/contacts")
@Consumes({"application/json"})
public void addContact(@RequestBody MyClass c) {

Where MyClass is a simple java class representing the request object (ie in this case you would just need one String class variable named param1.

If you are using springmvc, it comes with message converter for json. You may have to declare your pojo as a parameter in your method.

The problem was that the plugin from firefox didn't allow me to modify the headers, so when I tryed with text/plain on chrome with postman it worked.

Thanks anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM