![](/img/trans.png)
[英]Java XML DocumentBuilderFactory write empty tags <Tag /> from null values
[英]“document: null” from DocumentBuilderFactory on an XML response?
我正在创建jUnit测试,以检查为客户端应用程序获取XML的代理Servlet是否返回了它们而没有损坏或任何更改。
在我的jUnit类中,我有一个doGet方法,该方法执行对代理Servlet的HTTP get请求,并向其传递一个URL,该URL最后带有GET参数。
应将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]
我正在尝试获取作为XML文档的HTTP响应的字符串值,因此我可以将其与另一个字符串进行比较以确保它是正确的。
如何获得此字符串值?
谢谢
使用Apache.IO.Utils Common Lib中的这段优雅的代码解决了该问题
org.apache.commons.io.IOUtils.toString(new URL(requestURL));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.