问题描述
我有一个问题需要理解 URLConnection
类中 connect()
方法的含义。在下面的代码中,如果我使用 connect()
方法,如果我不使用它,我会得到相同的结果。
I have a problem to understand the meaning of the connect()
method in the URLConnection
class. In the following code, if I use the connect()
method, I get the same result if I don't use it.
为什么(或何时)我需要使用它?
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);
}
推荐答案
您并不总是需要显式调用connect方法以启动连接。
You are not always required to explicitly call the connect method to initiate the connection.
依赖于连接的操作,例如 getInputStream
, getOutputStream 等将隐式执行连接。
Operations that depend on being connected, like
getInputStream
, getOutputStream
, etc, will implicitly perform the connection, if necessary.
这是oracle doc
Here's the oracle doc link
这篇关于Java URLConnection - 我什么时候需要使用connect()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!