"文件:null"来自DocumentBuilderFactory的XML响应?

时间:2013-04-24 10:02:25

标签: java xml string httpurlconnection

我正在创建jUnit测试,以检查为客户端应用程序提取XML的代理servlet是否返回它们而没有损坏或任何更改。

在我的jUnit类中,我有一个doGet方法,它向代理servlet执行我的HTTP get请求,它在末尾传递一个带有GET参数的URL

应该将XML响应接收回客户端(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();
}

这是我的输出:

  

     

200

     

     

[#document:null]

我正在尝试获取HTTP响应的字符串值,这是一个XML文档,所以我可以将它与另一个字符串进行比较,以确保它是正确的。

如何获取此字符串值?

由于

1 个答案:

答案 0 :(得分:0)

使用Apache.IO.Utils Common Lib

中的这一优雅代码解决了这个问题
org.apache.commons.io.IOUtils.toString(new URL(requestURL));