Tôi đang cố gắng phân tích cú pháp và XML response
, nhưng tôi thất bại thảm hại. Ban đầu, tôi nghĩ rằng rằng xml
không được trả lại trong phản hồi, vì vậy tôi đã tạo mã bên dưới với liên kết trực tiếp đến tệp trực tuyến xml
của tôi. Tôi có thể in XML
vào màn hình mà không gặp vấn đề gì. Tuy nhiên, khi tôi gọi phương thức phân tích cú pháp của mình, tôi nhận được Kết thúc sớm của tệp.Tại sao tôi nhận được lỗi này Kết thúc sớm của tệp?
Nó hoạt động nếu tôi vượt qua URL trực tiếp:
- builder.parse ("");
nhưng không khi tôi đã thông qua một InputStream:
builder.parse (connection.getInputStream());
try { URL url = new URL(xml); URLConnection uc = url.openConnection(); HttpURLConnection connection = (HttpURLConnection)uc; connection.setDoInput(true); connection.setDoOutput(true); InputStream instream; InputSource source; //get XML from InputStream if(connection.getResponseCode()>= 200){ connection.connect(); instream = connection.getInputStream(); parseDoc(instream); } else{ instream = connection.getErrorStream(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } static void parseDoc(InputStream instream) throws ParserConfigurationException, SAXException, IOException{ BufferedReader buff_read = new BufferedReader(new InputStreamReader(instream,"UTF-8")); String inputLine = null; while((inputLine = buff_read.readLine())!= null){ System.out.println(inputLine); } DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); factory.isIgnoringElementContentWhitespace(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(instream); }
Các lỗi Tôi nhận:
[Fatal Error] :1:1: Premature end of file.
org.xml.sax.SAXParseException: Premature end of file.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at com.ameba.api.network.MainApp.parseDoc(MainApp.java:78)
at com.ameba.api.network.MainApp.main(MainApp.java:41)
Bạn có tệp XML bạn đang cố gắng phân tích cú pháp không. Kết thúc sớm của tệp cho biết tệp XML của bạn chưa hoàn chỉnh, vì bạn đang sử dụng kết nối URL ở đây, tôi nghi ngờ sự cố mạng. Cách tốt nhất để giải quyết vấn đề này là nắm bắt tệp XML này bằng cách sử dụng công cụ theo dõi hoặc công cụ giám sát TCP và sau đó kiểm tra xem nó có hoàn thành – NiranjanBhat
@NiranjanBhat hay không. Có XMl là đầy đủ và hợp lệ. Tôi đã phân tích cú pháp xml này bằng một liên kết trực tiếp. Có vẻ như lỗi này chỉ phát sinh khi sử dụng InputStream. – Fabii
Tại sao bạn làm POST nhưng không gửi bất kỳ dữ liệu nào? – EJP