真的有必要使用url.openConnection()吗?

Is it really necessary to use url.openConnection()?

众所周知,这两个代码会产生相同的结果

public class MainApp {
    public static void main(String[] args) throws IOException {
        URL google = new URL("http://www.google.com");
        google.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(google.openStream()));
        reader.lines().forEach(System.out::println);
    }
}

public class MainApp {
    public static void main(String[] args) throws IOException {
        URL google = new URL("http://www.google.com");
        BufferedReader reader = new BufferedReader(new InputStreamReader(google.openStream()));
        reader.lines().forEach(System.out::println);
    }
}

那么使用 google.openConnection()?

有什么意义

因为 openStream() 的代码是:

public final InputStream openStream() throws java.io.IOException {
    return openConnection().getInputStream();
}

确实有点多余

但如果我是你,如果我 openConnection()d,我会在返回的 URLConnection 上得到 InputStream

openConnection() 不会 修改 URL 对象,它 return 是您随后可以使用的 URLConnection 实例。问题中的代码忽略了 openConnection() 的 return 值,因此,在这种情况下,它确实没有意义。它只有在你实际对这个连接对象做一些事情时才有用,例如,修改它的超时:

URL google = new URL("http://www.google.com");
URLConnection conn = google.openConnection();
conn.setTimeout(7); // just an example 
BufferedReader reader = 
    new BufferedReader(new InputStreamReader(conn.getInputStream()));
reader.lines().forEach(System.out::println);

可能是此方法的 javadoc 帮助:

public java.net.URLConnection openConnection() throws java.io.IOException

Returns a URLConnection instance that represents a connection to the remote object referred to by the URL. A new instance of URLConnection is created every time when invoking the URLStreamHandler.openConnection(URL) method of the protocol handler for this URL.

It should be noted that a URLConnection instance does not establish the actual network connection on creation. This will happen only when calling URLConnection.connect().

If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned, and for JAR a JarURLConnection will be returned.

如果您想为连接添加一些特定的连接属性,请使用此选项。

例如:

URLConnection urlConnection = google.openConnection();

urlConnection.setReadTimeout(1000);
urlConnection.setConnectTimeout(1000);