gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:44:12 25 4
gpt4 key购买 nike

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

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() 有什么意义呢?

最佳答案

可能是此方法的 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);

关于java - 真的有必要使用 url.openConnection() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38655323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com