大家好目前正在开发一个需要解析 xml 文档以便对用户进行身份验证的应用程序。我正在使用 java.net.* 包的 URLConnection 类连接到特定的 URL,它以 xml 形式返回其响应格式。当我尝试使用 jdom 解析文档时,出现以下错误:
org.jdom2.input.JDOMParseException:第 1 行错误:文件过早结束
任何人都可以查明问题并帮助我解决问题吗?谢谢,这是我的代码的一部分
try {
String ivyString = "http://kabugi.hereiam.com/?username=" + ivyUsername + "&password=" + ivyPassword;
URL authenticateURL = new URL(ivyString);
URLConnection ivyConnection = authenticateURL.openConnection();
HttpURLConnection ivyHttp = (HttpURLConnection) ivyConnection;
System.out.println("Response code ==>" + ivyHttp.getResponseCode());
if (ivyHttp.getResponseCode() != 200) {
ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid username or password!", ""));
page = "confirm.xhtml";
} else {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(ivyConnection.getInputStream()));
String inline = "";
while ((inline = inputReader.readLine()) != null) {
System.out.println(inline);
}
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(ivyConnection.getInputStream());
Element rootNode = document.getRootElement();
List list = rootNode.getChildren("data");
for (int i = 0; i < list.size(); i++) {
Element node = (Element) list.get(i);
System.out.println("Element data ==>" + node.getChildText("username"));
System.out.println("Element data ==>" + node.getChildText("password"));
}
page = "home.xhtml";
}
} catch (Exception ex) {
ex.printStackTrace();
// ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid username or password!", ""));
}
最佳答案
看起来像,因为您正在读取输入流两次。一次打印它,然后构建文档。当您到达构建 Document 对象的位置时,输入流已被完全读取并结束。试试下面的代码,它只读取一次流
BufferedReader inputReader = new BufferedReader(new InputStreamReader(ivyConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String inline = "";
while ((inline = inputReader.readLine()) != null) {
sb.append(inline);
}
System.out.println(sb.toString());
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(new ByteArrayInputStream(sb.toString().getBytes()));
关于java - 从输入流 Java 解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12466529/