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

本文对比分析了URLConnection类中的openStream()与openConnection()方法在从URL获取数据时的应用场景及优缺点。当URL指向的资源为纯文本且编码为ASCII时,推荐使用openStream()方法;其他情况下,则建议使用openConnection()方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们知道,从 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()方法吧。






评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值