Java URLConnection - 我什么时候需要使用 connect() 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16122999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:58:25  来源:igfitidea点击:

Java URLConnection - When do I need to use the connect() method?

javaconnecthttpurlconnectionurlconnection

提问by kappa

I have a problem to understand the meaning of the connect()method in the URLConnectionclass. In the following code, if I use the connect()method, I get the same result if I don't use it.

我在理解类中connect()方法的含义时遇到了问题URLConnection。在下面的代码中,如果我使用该connect()方法,如果我不使用它,我会得到相同的结果。

Why (or when) do I need to use it?

为什么(或何时)我需要使用它?

URL u = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();

conn.connect();//with or without it I have the same result

InputStream in = conn.getInputStream();
int b;
while ((b = in.read()) != -1) {
 System.out.write(b);
}

回答by swagat

You are not always required to explicitly call the connect method to initiate the connection.

您并不总是需要显式调用 connect 方法来启动连接。

Operations that depend on being connected, like getInputStream, getOutputStream, etc, will implicitly perform the connection, if necessary.

如有必要,依赖于连接的操作(如getInputStreamgetOutputStream等)将隐式执行连接。

Here's the oracle doc link

这是 oracle 文档链接

回答by Amanda

HttpURLConnection conn = (HttpURLConnection) u.openConnection();

only creates an Object

只创建一个对象

connect()method is invoked by conn.getInputStream();

connect()方法被调用 conn.getInputStream();