ehsan ehsan - 4 months ago 10
Java Question

Is it really necessary to use url.openConnection()?

As we all know both these codes will yield the same result

public class MainApp {
public static void main(String[] args) throws IOException {
URL google = new URL("http://www.google.com");
google.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(google.openStream()));
reader.lines().forEach(System.out::println);
}
}


and

public class MainApp {
public static void main(String[] args) throws IOException {
URL google = new URL("http://www.google.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(google.openStream()));
reader.lines().forEach(System.out::println);
}
}


So what's the point in using
google.openConnection()?

Answer

May be javadoc for this method helps:

public java.net.URLConnection openConnection() throws java.io.IOException

Returns a URLConnection instance that represents a connection to the remote object referred to by the URL. A new instance of URLConnection is created every time when invoking the URLStreamHandler.openConnection(URL) method of the protocol handler for this URL.

It should be noted that a URLConnection instance does not establish the actual network connection on creation. This will happen only when calling URLConnection.connect().

If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned, and for JAR a JarURLConnection will be returned.

Use this if you want to add some specific connectivity properties to your connection.

For example:

URLConnection urlConnection = google.openConnection();

urlConnection.setReadTimeout(1000);
urlConnection.setConnectTimeout(1000);