java – 为什么我应该使用url.openStream而不是url.getContent?
我想检索一个网址的内容.
与Python相似: 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. 在我看来,应该完美无缺. 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. 解决方法
正如你所说,文档说URL.getContent()是openConnection().getContent()的快捷方式,所以我们需要查看
the documentation for
URLConnection.getContent() .
我们可以看到这返回一个Object,其类型由响应的content-type头字段确定.此类型确定将使用的 换句话说,您获得的对象类型将取决于所提供的内容.例如,如果MIME类型是image / png,则返回String是没有意义的. 这就是为什么在链接到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将返回一个字符串. sun.net.www.content包中定义了默认内容处理程序,但正如您所看到的,它们正在为您返回流. 您可以创建自己的ContentHandler,它确实返回一个String,但是按照您的建议读取Stream可能会更容易. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |