首页 > 解决方案 > 致命错误:1:1:文件过早结束 - 在 Url.openStream() / 罗马工具中的新 XmlReader 中

问题描述

从一天开始挑战我的小程序片段,

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import com.rometools.rome.io.FeedException;

public class Test {

public static void main(String[] args) throws IllegalArgumentException, FeedException, IOException {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputStream openStream = new URL("http://www.livemint.com/rss/money").openStream();
        Document doc = db.parse(openStream);
        System.out.println(doc.getDocumentURI());
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

所有这些实验都是从 rome tools 解析器代码开始的,这在不同的方法中也给了我同样的错误。

SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(url));
feed.getEntries();

在创建新的 xml Reader 时抛出异常,所以我用不同的方法编写了一个测试程序。现在两者都抛出相同的错误,

[致命错误]:1:1:文件过早结束。

我必须从 url 获取 xml 响应,但不能这样做。

标签: javaxmlsaxparserrome

解决方案


从 Java 代码向这个 URL 发送一个 GET 请求说:

Sending 'GET' request to URL : http://www.livemint.com/rss/money
Response Code : 301

因此,由于请求失败,响应中不存在 XML。请检查 API 并查看是否必须在 HTTP 请求中包含任何额外参数。

我使用以下代码连接到 URL:

  public static String getUrlResponse(String url) throws IOException {
             URL obj = new URL(url);
             HttpURLConnection con = (HttpURLConnection) obj.openConnection();
             // optional default is GET
             con.setRequestMethod("GET");
             //add request header
             int responseCode = con.getResponseCode();
             System.out.println("\nSending 'GET' request to URL : " + url);
             System.out.println("Response Code : " + responseCode);
             BufferedReader in = new BufferedReader(
                     new InputStreamReader(con.getInputStream()));
             String inputLine;
             StringBuffer response = new StringBuffer();
             while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
             }
             in.close();
             //print in String
             return response.toString();
  }

推荐阅读