【问题标题】:"document: null" from DocumentBuilderFactory on an XML response?XML 响应中来自 DocumentBuilderFactory 的“文档:null”?
【发布时间】:2013-04-24 10:02:25
【问题描述】:

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

在我的 jUnit 类中,我有一个 doGet 方法,该方法执行我对代理 servlet 的 HTTP 获取请求,它将一个带有 GET 参数的 URL 传递给它

应收到返回给客户端 (jUnit) 的 XML 响应。

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]

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

我如何得到这个字符串值?

谢谢

【问题讨论】:

标签: java xml string httpurlconnection


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2014-05-10
    • 2017-01-09
    • 2011-12-07
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多