Programming Tutorials

URLConnection sample program in Java

By: Ivan Lim in Java Tutorials on 2022-09-15  

URLConnection is a general-purpose class for accessing the attributes of a remote resource. Once you make a connection to a remote server, you can use URLConnection to inspect the properties of the remote object before actually transporting it locally. These attributes are exposed by the HTTP protocol specification and, as such, only make sense for URL objects that are using the HTTP protocol. We'll examine the most useful elements of URLConnection here.

Here's an example program that demonstrates the use of URLConnection in Java:

import java.net.*;
import java.io.*;

public class URLConnectionDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://example.com/");
            URLConnection urlConn = url.openConnection();
            
            // Set request properties
            urlConn.setRequestProperty("User-Agent", "Mozilla/5.0");

            // Get content type
            String contentType = urlConn.getContentType();
            System.out.println("Content Type: " + contentType);

            // Get content length
            int contentLength = urlConn.getContentLength();
            System.out.println("Content Length: " + contentLength);

            // Get last modified date
            long lastModified = urlConn.getLastModified();
            System.out.println("Last Modified: " + lastModified);

            // Get input stream
            InputStream input = urlConn.getInputStream();

            // Read the content of the URL
            int c;
            while ((c = input.read()) != -1) {
                System.out.print((char) c);
            }
            input.close();
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}

In this example, we create a URL object for the URL we want to access, then create a URLConnection object by calling the openConnection() method of the URL object.

We set some request properties on the URLConnection object, such as the user agent string, then retrieve some information about the content we're accessing, such as the content type, content length, and last modified date.

Finally, we get an input stream from the URLConnection object and read the content of the URL using a loop that reads each character from the input stream and prints it to the console.

Note that we wrap the entire code in a try-catch block to handle any IOException that may be thrown during the process of accessing the URL.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)