为什么我收到此错误过早结束文件?

2022-09-01 11:53:16

我试图解析一个,但我失败了。我最初认为响应中没有返回,所以我制作了下面的代码,并直接链接到我的在线文件。我能够毫无问题地打印到屏幕。但是,当我调用我的解析方法时,我得到的文件过早结束。XML responsexmlxmlXML

如果我直接传递URL,它的工作原理:

  • builder.parse(“”);

但是当我传递输入流时失败:

  • 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);
    }
    

我遇到的错误:

    [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)

答案 1

当您执行此操作时,

while((inputLine = buff_read.readLine())!= null){
        System.out.println(inputLine);
    }

您消耗了内流中的所有内容,因此内流是空的。现在,当尝试执行此操作时,

Document doc = builder.parse(instream);

解析将失败,因为您已将其传递为空流。


答案 2

您收到错误是因为SAXBuilder不够智能,无法处理“空白状态”。因此,它至少会查找一个声明,当该声明导致无数据响应时,它会创建您看到的异常,而不是报告空状态。<xml ..>


推荐