繁体   English   中英

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

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

我有一个问题需要理解URLConnection类中connect()方法的含义。 在下面的代码中,如果我使用connect()方法,如果我不使用它,我会得到相同的结果。

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

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方法来启动连接。

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

这是oracle doc 链接

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

只创建一个Object

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM