Java 为什么我应该使用url.openStream而不是url.getContent?
我想检索url的内容。 与蟒蛇相似:Java 为什么我应该使用url.openStream而不是url.getContent?,java,Java,我想检索url的内容。 与蟒蛇相似: html_content = urllib.urlopen("http://www.test.com/test.html").read() 在示例()中,您经常会看到以下代码: URL url = new URL("http://www.test.com/test.html"); String foo = (String) url.getContent(); getContent的描述如下所示: Gets the contents of this URL
html_content = urllib.urlopen("http://www.test.com/test.html").read()
在示例()中,您经常会看到以下代码:
URL url = new URL("http://www.test.com/test.html");
String foo = (String) url.getContent();
getContent的描述如下所示:
Gets the contents of this URL. This method is a shorthand for: openConnection().getContent()
Returns: the contents of this URL.
在我看来,这应该很好。
Buuut显然此代码不起作用,因为它会引发错误:
Exception in thread "main" java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream cannot be cast to java.lang.String
显然,它返回一个inputStream
所以我问自己:这个函数的目的是什么,它没有做它看起来做的事情?
为什么文档中没有关于怪癖的提示?
为什么我会在几个例子中看到它?
还是我弄错了
建议的解决方案()是使用url.openStream()然后读取流。您误解了“内容”的含义。您希望它返回一个包含HTML的字符串,但它返回一个HttpInputStream。为什么?因为请求的URL是html网页。另一个有效的URL可能是
http://www.google.com/logo.png
。此URL不包含字符串内容。这是一个图像。正如您所说,文档中说URL.getContent()
是openConnection().getContent()的快捷方式,所以我们需要查看
我们可以看到,这将返回一个对象
,其类型由响应的内容类型
头字段确定。此类型确定将要使用的。因此,ContentHandler
将基于MIME类型的数据转换为适当的Java对象类
换句话说,您获得的对象类型将取决于所服务的内容。例如,如果MIME类型是image/png
,那么返回字符串就没有意义了
这就是为什么在您链接到java2s.com的示例代码中,他们会检查返回对象的类:
try {
URL u = new URL("http://www.java2s.com");
Object o = u.getContent();
System.out.println("I got a " + o.getClass().getName());
} catch (Exception ex) {
System.err.println(ex);
}
所以你可以说stringfoo=(String)url.getContent()
如果您知道您的ContentHandler
将返回一个字符串
在sun.net.www.content
包中定义了默认的内容处理程序,但正如您所看到的,它们正在为您返回流
您可以创建自己的ContentHandler
,返回字符串
,但按照您的建议读取流可能会更容易。您可以使用的方法更容易地读取字符串的URL