简体   繁体   English

在Restful上使用@POST进行JSON

[英]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. 我正在尝试在POST方法上获取JSON值,但我不知道该怎么做。

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: 我正在使用以下外观通过firefox RestClient发送JSON值:

{"param1":"value"}

How can I take this value? 我该如何取值?

We also have this error message: 415 Unsupported Media Type 我们也有此错误消息:415不支持的媒体类型

Thanks. 谢谢。

Make sure you are actually sending a post and the content-type of your request is application/json. 确保您实际上正在发送帖子,并且您请求的内容类型为application / json。 To consume this with spring MVC you can use the @RequestBody annotation: 要在spring MVC中使用它,可以使用@RequestBody批注:

@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. MyClass是代表请求对象的简单Java类(即,在这种情况下,您只需要一个名为param1的String类变量即可。

If you are using springmvc, it comes with message converter for json. 如果您使用的是springmvc,则它带有用于json的消息转换器。 You may have to declare your pojo as a parameter in your method. 您可能必须在方法中声明pojo作为参数。

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. 问题是firefox的插件不允许我修改标题,因此当我尝试使用邮递员在chrome上使用text / plain时,它可以工作。

Thanks anyway. 不管怎么说,还是要谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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