繁体   English   中英

REST API如何接收请求正文数据?

[英]How REST API receive request body data?

我在struts2中使用操作将json发布到REST API。

现在发布Jan对象,如下

  1. 使用JSONObject.fromObject(Object object).toString
  2. 然后使用postmethod.setRequestEntity()
  3. 最终客户执行帖子的方法

那么REST API应该如何接收数据?

这是一段代码:

@POST
    @Path("addUser")
    @Produces("text/plain")
    @Consumes(MediaType.APPLICATION_JSON)
    public String addUser() {

    }; 
  1. 首先,我将@XmlRootElement(name="user")到我的模型中-用户,
  2. 然后将用户转换为xml,当然,您应该设置Content-Type", MediaType.APPLICATION_ATOM_XMl

  3.  @POST @Path("addUser") @Produces("text/plain") @Consumes(MediaType.APPLICATION_ATOM_XML) public String addUser(User user) {} 
  4.  <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param> 

到web.xml

最终您可以获得用户。

如果我理解您的问题,要在REST API中接收JSON字符串,可以使用JAXB。 您可以参考以下内容。

REST API

@POST
@Path("addUser")
@Produces("text/plain")
@Consumes(MediaType.APPLICATION_JSON)
public String addUser(Student s) {
    //Your logic here
    return "user added";
}; 

学生的JAXB表示形式。

public class Student {
    String id;

    String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    String age;

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public Student(String id, String name, String age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Student() {

    }
}

发布学生JSON字符串时,您将在addUser方法中获得Raw Student对象。 如果我的理解是错误的,请纠正我。

如果要使用带有jersey和apache-cxf的Rest API(JAX-WS-RS)在后端代码中访问正文部分,则需要配置此类的rest包。

  @Path("/student")  //path of rest package of class 
  @Consumes("application/json")  //If you want to consumed produced json
  @Produces("application/json") //If you want to produced json
  public class StudentRest{

     Student student=new Student();

     @GET
     @Path("returnstudent")
     public Student ReturnStudentMethod()
     {
            return student;
     }

     //if you want to receive or produced some specific type then write
     @GET
     @Produced("application/pdf")
     @Path("returnpdffile")
     public Response ReturnPdfFile()
     {
            return file;
     }

}

And also you need to set web.xml if you are using jaxrs with jersey
   <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
   </init-param>

暂无
暂无

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

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