您的位置:首页 > 运维架构

关于openStream方法和openConnection方法的区别

2016-03-18 22:53 676 查看
我们知道,从 URL获取数据的方法,有下面几种:

URLConnection
openConnection()

Returns a
URLConnection
instance
that represents a connection to the remote object referred to by the
URL
.
URLConnection
openConnection(Proxy proxy)

Same as
openConnection()
,
except that the connection will be made through the specified proxy; Protocol handlers that do not support proxing will ignore the proxy parameter and make a normal connection.
InputStream
openStream()
<最常用>

Opens a connection to this
URL
and
returns an
InputStream
for reading from that connection.
Object
getContent()

Gets the contents of this URL.
Object
getContent(Class[] classes)

Gets the contents of this URL.
其中,openStream方法和openConnection方法两个方法很像,而且效果一样,那么应该选择哪一个方法好呢?

其实底层的实现,openStream()方法的实现也是调用了 openConnection生成一个 URLConnection 对象,然后再通过这个对象调用的 getInputStream()方法的,《Java网络编程》说“如果希望与服务器直接通信,应当使用这个方法”。这样显式生成了·URLConnection对象的好处应该是可以调用这个对象的一些方法,以及获取它的一些字段吧。因此,当你确定
URL 指向的绝对是文本且编码格式为ASCII时,使用 openStream()方法比较方便,除此之外,就用 openConnection()方法吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: