37

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);
}
Moshe Katz
  • 15,992
  • 7
  • 69
  • 116
kappa
  • 520
  • 1
  • 5
  • 11

2 Answers2

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

only creates an Object

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

joce
  • 9,624
  • 19
  • 56
  • 74
Amanda Jiang
  • 486
  • 4
  • 2
35

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

Anirudha
  • 32,393
  • 7
  • 68
  • 89
swagat
  • 353
  • 3
  • 6