简体   繁体   中英

“document: null” from DocumentBuilderFactory on an XML response?

I am creating jUnit tests to check that my proxy servlet which fetches XMLs for a client application returns them without corruption or any changes.

In my jUnit class I have a doGet method which carries out my HTTP get requests to the proxy servlet, it passes it a URL with GET params at the end

An XML response should be received back to the client (jUnit).

protected String doGet() throws IOException, ParserConfigurationException, SAXException
{
    String requestURL = url + params;
    System.out.println(requestURL);
    // fetch XML from URL
        System.out.println(requestURL);

        URL url = new URL(requestURL);
        HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/xml");

        InputStream xml = connection.getInputStream();
        System.out.println(connection.getResponseMessage());
        System.out.println(connection.getResponseCode());

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        org.w3c.dom.Document text = db.parse(xml);
        System.out.print(text.getNodeValue());
        return text.toString();
}

Here is my output:

OK

200

null

[#document: null]

I am trying to get the string value of the HTTP response which is an XML document, so I can compare it with another string to make sure it is correct.

How do I get this string value?

Thanks

使用Apache.IO.Utils Common Lib中的这段优雅的代码解决了该问题

org.apache.commons.io.IOUtils.toString(new URL(requestURL));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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