Skip to main content

Java URLConnection Class

Introduction to Java URLConnection Class

In this tutorial, we will be delving into the Java URLConnection Class, an integral part of Java Networking. The URLConnection class is contained in the java.net package and is used to establish a connection to a remote server from a Java application. This class can be used to read from or write to the server.

What is the URLConnection Class?

URLConnection is an abstract class in Java that represents a communication link between the URL and the application. This class can be used to read, write, and manipulate data on the web.

Creating a URLConnection

To create a URLConnection, you use the URL.openConnection() method. Here is the general syntax:

URL url = new URL("http://www.example.com");
URLConnection connection = url.openConnection();

In the above code, we first create a URL object and then call the openConnection() method to obtain a URLConnection.

Reading from a URLConnection

Once you have established a connection, you can read data from the URL using the getInputStream() method. This method returns an InputStream that you can use to read data from the URL.

Here's an example:

URL url = new URL("http://www.example.com");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();

In this code, we first establish a connection to http://www.example.com. Then, we open an InputStream to the URL and read from it.

Writing to a URLConnection

Writing to a URLConnection is a bit more complicated. By default, a URLConnection is in 'read-only' mode. To write to it, you need to set its doOutput property to true.

Here's an example:

URL url = new URL("http://www.example.com");
URLConnection connection = url.openConnection();
connection.setDoOutput(true); // Enable writing
OutputStream stream = connection.getOutputStream();

In this code, we first establish a connection to http://www.example.com. Then, we enable writing to the URLConnection and open an OutputStream to it.

Other Useful Methods

The URLConnection class provides several other methods that you may find useful:

  • getContentLength(): Returns the size of the resource pointed by this URLConnection.
  • getContentType(): Returns the MIME type of the resource.
  • getLastModified(): Returns the date the resource was last modified.
  • getExpiration(): Returns the expiration date of the resource.

Conclusion

That's a basic overview of the Java URLConnection class. It provides a convenient way to communicate with remote servers in a Java application. However, do note that the URLConnection class is a low-level class and there are higher-level classes available that provide more functionality and easier use, such as the HttpURLConnection class.