0

I have a Play web app that makes an HTTP request to a server.

The request goes well: I get a response with an 200 status code and Content-type = "application/xml".

If I print to stdout the response body, I see a well-formed Xml doc.

However, if I try to create an org.w3c.dom.XML document from the response using WSResponse.asXml(), the method returns an empty document.

These are the relevant portions of my code:

private WSResponse sendPostRequest(String url, String body) {

    WSRequest request = WS.url(url);

    request.setHeader("Content-type", "application/x-www-form-urlencoded");

    return request.post(body).get(5000L);
}

And:

public Result requestDefaultImport() {

    String url = "some_url";
    String body = "some_body";

    WSResponse response = sendPostRequest(url, body);

    System.out.println(response.getBody()); //prints well-formed Xml

    Document xmld = response.asXml(); 
    System.out.println(xmld); //prints: #[null document]


    return ok();
}

What am I doing wrong?

Eduard
  • 25
  • 8

2 Answers2

2

Try this code:

Document doc = request().body().asXml();
Source source = new DOMSource(doc);
StringWriter stringWriter = new StringWriter();
StreamResult result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
javax.xml.transform.Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
String xmlStr = stringWriter.getBuffer().toString();
System.out.println(xmlStr);

or this if consuming from SOAP:

Document doc = soapBody.extractContentAsDocument();
Source source = new DOMSource(doc);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
strSoapBody = stringWriter.getBuffer().toString();
Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
0

As far as I can see you are printing a string at

System.out.println(response.getBody());

However, you are printing a org.w3c.dom.Document at

 System.out.println(xmld);

The solution to converting a Document to a string can be found at

How do I convert a org.w3c.dom.Document object to a String?

Community
  • 1
  • 1
David Gordon
  • 287
  • 4
  • 17