user2824073
user2824073

Reputation: 2485

how to consume XML in a REST WebService?


I have an HTML form which submits an XML using a textarea field:

 <form  action="rest" method="POST">
   <textarea name="xml" rows="10" cols="30" ></textarea>
   <input type="submit" value="Invoke REST">
 </form>

Now i want to consume the XML in a REST Webservices (I'm using Java EE 7 and WildFly CR1). I've tried using:

 @POST
 @Consumes(MediaType.APPLICATION_XML) 
 public Response createItemFromXML(@FormParam("xml") Customer c) {

     ejb.addToList(c);

     return Response.ok("Created customer ").build();

}

Which leads to java.lang.RuntimeException: Unable to find a constructor that takes a String param or a valueOf() or fromString() method for javax.ws.rs.FormParam("xml") on public javax.ws.rs.core.Response com.sample.SimpleRESTService.createItemFromXML(com.sample.Customer) for basetype: com.sample.SimpleProperty

Do I have to use a Stream as form parameter (and convert manually to XML) or is there a simpler way to do it ?

EDIT: I've tried as well with:

  @POST
  @Consumes(MediaType.APPLICATION_XML)
  public Response createPropertyFromXml(  Customer c) {

   ejb.addToList(c);
   return Response.ok("Created customer " + n).build(); 
 } 

However the error is now: javax.ws.rs.NotSupportedException: Cannot consume content type Seems it cannot be converted from a form field to XML automatically.... Thanks

Upvotes: 1

Views: 2018

Answers (1)

Xavier Coulon
Xavier Coulon

Reputation: 1600

AFAIK, you should either set the c parameter as a String and then parse it in your createItemFromXML method, or your you could remove the @FormParam annotation on the method argument and use JAXB annotations on your Customer class. In that later case, the underlying JAX-RS implementation of Wildfly will convert the incoming XML request body into an instance of Customer.

Upvotes: 1

Related Questions