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

别来无恙 提交于 2019-11-27 03:02:56

问题


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);
}

回答1:


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

only creates an Object

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




回答2:


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

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

Here's the oracle doc link



来源:https://stackoverflow.com/questions/16122999/java-urlconnection-when-do-i-need-to-use-the-connect-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!