我为什么要使用url.openStream而不是url.getContent?

时间:2012-03-20 21:34:42

标签: java

我想检索网址的内容。 与pythons类似:

html_content = urllib.urlopen("http://www.test.com/test.html").read()

在示例(java2s.com)中,您经常会看到以下代码:

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。

所以我问自己:这个功能的目的是什么,它没有做它似乎做的事情? 为什么在文档中没有暗示它的怪癖? 为什么我在几个例子中看到了它?

或者我错了?

建议的解决方案(stackoverflow)是使用url.openStream()然后读取Stream。

3 个答案:

答案 0 :(得分:12)

正如您所说,文档说URL.getContent()openConnection().getContent()的快捷方式,因此我们需要查看the documentation for URLConnection.getContent()

我们可以看到这会返回一个Object,其类型由响应的content-type标头字段决定。此类型确定将使用的ContentHandler。因此ContentHandler将基于其MIME类型的数据转换为适当的Java Object类。

换句话说,您获得的对象类型取决于所提供的内容。例如,如果MIME类型为String,则返回image/png是没有意义的。

这就是为什么在链接到java2s.com的示例代码中,他们检查返回的Object的类:

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);
}

如果您知道String foo = (String) url.getContent();将返回ContentHandler,则可以说String

sun.net.www.content包中定义了默认内容处理程序,但您可以看到它们正在为您返回流。

您可以创建自己的ContentHandler并返回String但是按照您的建议阅读流可能会更容易。

答案 1 :(得分:2)

你误解了什么"内容"手段。您希望它返回包含HTML的String,但它返回一个HttpInputStream。为什么?因为请求的URL是html网页。另一个有效的网址可能是http://www.google.com/logo.png。此URL不包含字符串内容。这是一张图片。

答案 2 :(得分:2)

您可以使用GuavaResources.toString(URL, Charset)方法更轻松地读取字符串的网址。