嗨,大家目前正在研究需要解析xml文档以验证用户的应用程序。使用java.net。*包的URLConnection类来连接到特定的URL以xml格式返回其响应。当我尝试解析使用JDOM文档时,我得到以下错误:
org.jdom2.input.JDOMParseException: Error on line 1: Premature end of file
XML从输入流解析Java
谁能找出问题所在,并协助我有办法补救吗?谢谢,这里是我的部分代码
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!", ""));
}
这个问题可以简单地通过InputStream中返回的数据是错误格式XML - 你检查的实际内容? –
正如@mattb所述,您检索的内容可能不是有效的XML文档。为了解析HTML页面,您可以使用更灵活的库,例如JSoup,请参阅:http://jsoup.org – Alex
或者您可以使用流畅的API“RestAssured”或另一个名为“RestEasy”的项目... – djangofan