我正在尝试获取股票的最新股价。作为示例使用的 URL 是
String stockURL=http://www.google.com/ig/api?stock=ADSL
.
我可以在我的浏览器中打开这个链接。为了解析执行 URL 后得到的文档,我编写了以下代码。
public static void main(String[] args) {
URL url;
try {
url = new URL(stockUrl);
GettingCurrentStockPrice gettingCurrentStockPrice = new GettingCurrentStockPrice();
gettingCurrentStockPrice.readDoc(gettingCurrentStockPrice
.parse(url));
} catch (MalformedURLException e) {
System.out.println("Encountered MalformedURLException:" + e);
} catch (DocumentException e) {
System.out.println("Encountered DocumentException:" + e);
}
}
private Document parse(URL url) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(url);
return document;
}
private void readDoc(Document document) {
Element root = document.getRootElement();
// iterate through child elements of root
for (Iterator<Element> i = root.elementIterator(); i.hasNext();) {
Element element = (Element) i.next();
System.out.println(element);
}
for (Iterator i = root.elementIterator("company data"); i.hasNext();) {
Element compName = (Element) i.next();
System.out.println("compName-->" + compName);
}
}
在运行程序时,我以,
Encountered DocumentException:org.dom4j.DocumentException: Connection timed out: connect Nested exception: Connection timed out: connect
.
为什么无法打开给定的 URL?
更新:问题来parse()
了render.read(url);
。