嗨,大家目前正在研究需要解析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