URLConnection Class in Java

The URLConnection class is used for accessing the attribute of remote resource.

URLConnection is the superclass of all the classes that represent a communication link between application and a URL.

URLConnection Class Methods

MethodsDescription
int getContentLength()Returns the size in byte of content associated with resource.
String getContentType()Returns type of content found in the resource. If the content is not available, it returns null.
long getDate()Returns the time and date of the response.
long getExpiration()Returns the expiry time and date of the resource. If the expiry date is unavailable, it return zero.
long getLastModified()Returns the time and date of the last modification of the resource.
InputStream getInputStream() throws IOException()Returns an InputStream that is linked to the resource.
String getRequestProperty(String key)Returns the value of the named general request property for the given connection.

Example: Illustrating different methods of URLConnection class

import java.net.*;
import java.io.*;
import java.util.Date;
import java.lang.*;
public class UMLConDemo
{
    public static void main(String args[]) throws Exception
    {
        int c;
        URL url = new URL("http://www.tutorialride.com/java-technologies.htm");
        URLConnection urlc = url.openConnection();
        long d = urlc.getDate();
        if(d == 0)
             System.out.println("No date Information.");
        else
             System.out.println("Date: "+new Date(d));
        System.out.println("Content Type: "+urlc.getContentType());
        int len = urlc.getContentLength();
        if(len == -1)
             System.out.println("Content length not available");
        else
             System.out.println("Lenght of the Content: "+len);
        d = urlc.getExpiration();
        if(d==0)
              System.out.println("No expiration information.");
        else
              System.out.println("Expires: " + new Date(d));
     }
}


Output:
No date Information.
Content Type: null
Content length not available
No expiration information.