Noname
Noname

Reputation: 349

Get the XML string posted to JAXB web service endpoint

I have configured a web service endpoint as below.

@POST
@Consumes({MediaType.APPLICATION_XML})
@Produces({MediaType.TEXT_PLAIN})
@Path("/post")
public String postPerson(Person pers) throws Exception{
    String xml_string_posted="?";
    System.out.println(<xml_string_posted>);
    JAXBContext jc = JAXBContext.newInstance(Person.class);
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource());

    }

My Question is very simple. Whenever there is POST request submitted to this endpoint like below, how can i get the whole XML string posted below into a variable.

POST /JX-1.0/service/person/post HTTP/1.1
Host: 
Content-Type: application/xml
X-Requested-With: XMLHttpRequest

<?xml version="1.0"?>
<a>
<b>&name;</b>
</a>

Upvotes: 0

Views: 208

Answers (1)

Arnaud Develay
Arnaud Develay

Reputation: 3970

Since HttpServletRequest#getInputStream() can only be used once, you will have to update the signature of your method if you want to obtain the raw body request.

You can for exemple, add a String parameter to your method. The payload will be assigned automatically to this variable.

@POST
@Consumes({MediaType.APPLICATION_XML})
@Produces({MediaType.TEXT_PLAIN})
@Path("/post")
public String postPerson(String bodyRequest) throws Exception{
    // your code...
}

As an alternative, you can use HttpServletRequest as below:

@POST
@Consumes({MediaType.APPLICATION_XML})
@Produces({MediaType.TEXT_PLAIN})
@Path("/post")
public String postPerson(@Context HttpServletRequest request) throws Exception{
    ServletInputStream inputStream = request.getInputStream();
    System.out.println(inputStream.isFinished());
    byte[] buffer = new byte[250];
    int read = inputStream.read(buffer);
    System.out.println(new String(buffer, 0, read));
    // ...
}

If you need the original signature, you can check this question : How to read request.getInputStream() multiple times

Upvotes: 1

Related Questions