我们知道,从 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生成一个 URLConnection 对象,然后再通过这个对象调用的 getInputStream()方法的,《Java网络编程》说“如果希望与服务器直接通信,应当使用这个方法”。这样显式生成了·URLConnection对象的好处应该是可以调用这个对象的一些方法,以及获取它的一些字段吧。因此,当你确定 URL 指向的绝对是文本且编码格式为ASCII时,使用 openStream()方法比较方便,除此之外,就用 openConnection()方法吧。