gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:18:52 28 4
gpt4 key购买 nike

我正在尝试解析 XML 响应,但失败得很惨。我一开始以为xml 只是没有在响应中返回,所以我制作了下面的代码,并直接链接到我的 xml 文件在线。我能够毫无问题地将 XML 打印到屏幕上。但是,当我调用我的解析方法时,我得到 Premature end of file.

如果我直接传递 URL 就可以了:

  • builder.parse("");

但是当我通过 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);
    }

我得到的错误:

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

最佳答案

当你这样做时,

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

您在流内消耗所有内容,因此流内是空的。现在尝试这样做时,

Document doc = builder.parse(instream);

解析将失败,因为您传递了一个空流。

关于java - 为什么我收到此错误文件过早结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10022796/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com