Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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); } 
like image 608
kappa Avatar asked Apr 20 '13 17:04

kappa


People also ask

What is the use of open connection method of URL connection class?

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.

What is the purpose of URL connection class?

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.

What is the difference between URLConnection and HttpURLConnection?

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.


2 Answers

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

only creates an Object

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

like image 178
Amanda Jiang Avatar answered Oct 04 '22 03:10

Amanda Jiang


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

like image 27
swagat Avatar answered Oct 04 '22 04:10

swagat