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); }
The openConnection() method returns a java. net. URLConnection, an abstract class whose subclasses represent the various types of URL connections. If you connect to a URL whose protocol is HTTP, the openConnection() method returns an HttpURLConnection object.
The Java URLConnection class represents a communication link between the URL and the application. It can be used to read and write data to the specified resource referred by the URL.
URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
only creates an Object
connect()
method is invoked by conn.getInputStream();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With