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

kappa picture kappa · Apr 20, 2013 · Viewed 19.3k times · Source

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

Answer

swagat picture swagat · Sep 11, 2013

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