Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey Consumes XML post

Tags:

post

xml

jersey

I want to make a Post to Jersey Rest service. What is the standard way of doing this?

@Post
@Consumes(MediaType.Application_xml)
public Response method(??){}
like image 818
Justin Avatar asked Jul 08 '10 13:07

Justin


Video Answer


1 Answers

Suppose you have a java bean say an employee bean such as. Add the tags to tell

@XmlRootElement (name = "Employee")
public class Employee {
    String employeeName;

    @XmlElement
    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
}

@XmlRootElement tells that this will be the main tag in xml. In this case you can specify a name for the main tag as well.

@XmlElement tells that this would be the sub tag inside the root tag

Say, the sample xml that will come as a part of body in the post request will look something like

<?xml version="1.0" encoding="UTF-8"?>
<Employee>
 <employeeName>Jack</employeeName>
</Employee>

When writing a webservice to acccept such an xml we can write the following method.

@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response getEmployee(Employee employee) {
     employee.setEmployeeName(employee.getEmployeeName() + " Welcome");
     return Response.status(Status.OK).entity(employee).build();
}

On calling this service, you will get the following xml as part of the response.

<Employee>
<employeeName> Jack Welcome </employeeName>
</Employee>

using @Xml...annotations, it becomes very easy to unmarshal and marshal the request and response objects.

Similar approach can be taken for JSON input as well as JSON output by just using the MediaType.APPLICATION_JSON instead of APPLICATION_XML

So for an xml as input, you can get an xml as an output as part of the http response. Hope this helps.

like image 99
rahul pasricha Avatar answered Sep 29 '22 21:09

rahul pasricha