从输入流 Java 解析 XML

bug*_*man 2 java xml parsing jdom

大家好,目前正在开发一个需要解析 xml 文档以便对用户进行身份验证的应用程序。我使用 java.net.* 包的 URLConnection 类连接到特定的 URL,该 URL 以 xml 格式返回其响应。当我尝试使用 jdom 解析文档时,出现以下错误:
org.jdom2.input.JDOMParseException: Error on line 1: Premature end of file

任何人都可以查明问题并帮助我采取补救措施吗?谢谢,这是我的代码的一部分

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!", ""));
}
Run Code Online (Sandbox Code Playgroud)

man*_*esh 5

看起来像是因为您正在读取输入流两次。一次打印它,下一步构建文档。当您到达构建 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()));
Run Code Online (Sandbox Code Playgroud)