java - 致命错误: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 响应,但不能这样做。
解决方案
从 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();
}
推荐阅读
- excel - 如何在宏 VBA 中使用循环进行分配?
- php - SQLSTATE [01000] SQLDriverConnect:0 [unixODBC] [驱动程序管理器]无法打开库“IBMDB2”:找不到文件
- python - 如何在 Python 中搜索每个本地文本文件?
- python - Pandas Dataframe 根据长度替换字符串
- arrays - 如何找到数组中某个元素的总数(C)
- sql - 如果不可用,则仅显示最短日期的数据,然后在 SQL 中可用的任何日期
- python - 我想从这个数据层中提取所有信息。但我做不到。我究竟做错了什么?
- javascript - 有条件的多个单选按钮显示/隐藏差异内容
- r - 在R中查找矩阵的行名的每个元素的等级
- javascript - 为什么没有将所需的属性添加到变量中?