It is essential to have a clear understanding of Java’s URLConnection class in order to streamline networking tasks.
This article explores its functionality, including establishing connections, reading and writing data, and utilizing advanced features.
With code examples and real-world use cases, you will discover the power of URLConnection in Java programming.
Let’s begin our networking journey with URLConnection.

URLConnection Fundamentals

URLConnection class in Java represents a connection to a URL resource.
It is used for connecting to a resource on the internet, such as a webpage or an API endpoint.
By establishing a URLConnection object, you can read from or write to the specified resource.

Establishing a Connection

Assuming you have a valid URL and the necessary permissions, establishing a connection using the URLConnection class in Java is relatively straightforward.
Here’s a basic outline of how you can do this:
1. Create a URL object with the desired URL.
2. Open a connection using the openConnection() method of the URL object.
3. Cast the returned URLConnection object to an appropriate subclass, such as HttpURLConnection for HTTP connections.
4. Proceed with reading from or writing to the connection as needed.

1. Creating a URL Object

Creating a URL object is the first step in establishing a connection using the URLConnection class.
This object represents the URL you want to connect to.
Here’s a simple example of creating a URL object in Java

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

When creating a URL object, ensure that the URL is properly formatted, including the protocol (e.g., http://), domain name, and any additional path or query parameters.

URL() constructor has been deprecated since java 20. You can use URI class to create its object as below

URL url = new URI("http://www.example.com").toURL();

2. Defining URLConnection

URLConnection object can be created using openConnection() method of URL.
openConnection() returns a URLConnection object that represents the communication link between your application and the URL.
Here’s how you can open a connection in Java:

import java.net.URL;
import java.net.URLConnection;

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

Above steps can be written in a one-liner as below

URLConnection urlConnection = new URL(url).openConnection();

After opening a connection, you can proceed with configuring the connection properties, reading from or writing to the connection, and handling any response data that you receive.

Reading Data from a URLConnection

For reading any data from a URL, we need to use its input stream.
We can read both text and binary data as explained next.

Reading Text Data

To get the input stream, use getInputStream() method of URLConnection.
Once we get an object of input stream, we can read the data received using a BufferedReader line by line as shown below

import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class URLReader {
  public static void main(String[] args) throws IOException {
    URL url = new URI("http://jsonplaceholder.typicode.com/posts/1").toURL();
    URLConnection connection = url.openConnection();
    InputStream inputStream = connection.getInputStream();
    BufferedReader in = new BufferedReader(
                       new InputStreamReader(inputStream));
    String inputLine;
    while ((inputLine = in.readLine()) != null)
      System.out.println(inputLine);
      in.close();
    }
}

Reading Binary Data

To read binary data, we can again use input stream and write it to ByteArrayOutputStream as shown below

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
    byteArrayOutputStream.write(buffer, 0, bytesRead);
}
byte[] binaryData = byteArrayOutputStream.toByteArray();

Writing Data to a URLConnection

Now, let’s explore the process of writing data to a URLConnection.
This involves using an OutputStream to send data to a specified URL.
Below is an example that writes data to a url with URLConnection

URLConnection connection = url.openConnection();
// Allows writing data to the connection
connection.setDoOutput(true); 
OutputStream outputStream = connection.getOutputStream();
String data = "Your data to be posted";
outputStream.write(data.getBytes());
outputStream.flush();

Working with Various Content Types

When working with URLConnection, you may encounter different content types.
We can set the content type of the data with setRequestProperty() of URLConnection and supplying it the property to set and its value.

Below is an example of configuring JSON as the content type.

connection.setRequestProperty("Content-Type", "application/json");

Setting Request Headers and Properties

Any HTTP request made through URLConnection can include custom headers and properties.
This allows you to send additional information in the request to the server.
One common use case is setting the “User-Agent” header to specify the client application making the request.
Below is an example code snippet demonstrating how you can set a custom header in a URLConnection:

URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "MyJavaApp/1.0");

Managing Connection Timeouts

Properties can be set on a URLConnection instance to manage connection timeouts.
The timeout values define how long the client will wait for a connection to be established or data to be read before throwing an exception.
Here is an example code snippet showing how you can set the connect and read timeouts for a URLConnection:

Properties props = new Properties();
props.put("connectTimeout", "5000");
props.put("readTimeout", "10000");

URLConnection connection = url.openConnection();
connection.setConnectTimeout(
            Integer.parseInt(props.getProperty("connectTimeout")));
connection.setReadTimeout(
            Integer.parseInt(props.getProperty("readTimeout")));

Timeouts are crucial for handling scenarios where a server is unresponsive or the network connection is slow.
By configuring these timeouts, you can ensure that your application does not hang indefinitely while waiting for a response from the server.

Handling Redirects and Proxies

For URLConnections that involve redirects or need to go through proxy servers, specific configurations are required.
Redirects are automatically followed by default, but you can disable this behavior if needed.
Proxies can be set explicitly to route the connection through a specific server.
Here is an example code snippet showing how you can handle redirects and proxies in a URLConnection:

URLConnection connection = url.openConnection();
// Disable automatic redirects
connection.setInstanceFollowRedirects(false); 
Proxy proxy = new Proxy(Proxy.Type.HTTP, 
                   new InetSocketAddress("proxy.example.com", 8080));
// Use a specific proxy server
connection = url.openConnection(proxy); 

Secure Connections with HTTPS

Connections established over HTTPS (Hypertext Transfer Protocol Secure) ensure secure communication between the client and server by encrypting the data transmitted.
To configure a URLConnection to use HTTPS, you need to set up the proper protocols and encryption algorithms.
Here’s a sample code snippet demonstrating how to establish an HTTPS connection:

// Set up an HTTPS connection
URL url = new URL("https://example.com");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
// Add any necessary configuration for HTTPS here

Authentication and Authorization Mechanisms

Authentication and authorization mechanisms are crucial for verifying the identity of clients and granting access to specific resources on the server.
This ensures secure interactions between parties. Implementing authentication and authorization in URLConnections involves setting up credentials and permissions.
Here’s an example code snippet that demonstrates how to handle authentication:

// Set up authentication for URLConnection
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);

Summing up

In this article, we understood how URLConnection class in java can be used to establish network connections and read/write data from it.
We also saw how to set request headers, properties and configure SSL connection for secured transport.