Java URL Class – Learn how to Address your resources on Internet

We all know a URL is a unique string of text that acts as an identity for all the resources on the Internet. URL helps in addressing the resources available on the Internet. In this article, we will cover the Java URL class which acts as a medium to connect to the internet.

Also, we will learn how to write Java programs that communicate with a URL (Uniform Resource Locator). We will also study what is URL and various segments of the URL. We will explore the URL class and URLConnection class in Java with examples for better understanding.

What is the URL?

URL, an acronym for Uniform Resource Locator, is a reference or address to unique resources such as a file, HTML page, or a document, etc. on the World Wide Web (network). The format of URL is in the string that describes the process to search for resources on the internet.

Segments of a URL

A URL can have numerous components. But it is mainly a three-segment framework and they are:

  • Protocol: HTTP (HyperText Transport Protocol) is the convention here. HTTP, HTTPS, FTP, and File are some examples of protocols.
  • Hostname or Server Name: Name of the server machine on which the resources are present.
  • File Name: The way name to the record on the machine.
  • Port Number: Port number is a number through which the URL connects to the web. If the URL does not specify any specific port, then the default port number is used.

Follow TechVidvan on Google & Stay updated with latest technology trends

What is Java URL Class?

Java URL class is the gateway to access the resources on the web. The object of the java.net.URL class represents the URL and this object manages all the information present in the URL string. There are many methods in the Java URL class to create the object of the URL class.

Constructors of Java URL Class

S.NConstructorDescription
1URL(String address) throwsMalformedURLExceptionIt creates a URL object from the given input  String.
2URL(String protocol, String host, String file)This constructor creates a URL object from the given input protocol, host, and file name.
3URL(String protocol, String host, int port, String file)This constructor creates a URL object from the specified protocol, hostname, port number and filename.
4URL(URL context, String spec)It makes a URL object by parsing the given String spec in the given context.
5URL(String protocol, String host, int port, String file, URLStreamHandler handler)This constructor makes a URL object from the specified protocol, hostname, port number, file, and handler.
6URL(URL context, String spec, URLStreamHandler handler)Makes a URL by parsing the given spec with the given input handler inside the given context.

Methods of Java URL Class

S.NMethod NameDescription
1public String toString()The toString() method returns the given URL object in the string form.
2public String getPath()This method returns the path of the URL. It returns null if the URL is empty.
3public String getQuery()This method gives the query part of the URL. A query is a part of the URL after the ‘?’ in the URL.
4public String getAuthority()This method returns the authority part of the URL and null if it is empty.
5public String getHost()This method gives the hostname associated with the URL in IPv6 format
6public String getFile()This method returns the filename of the URL.
7Public int getPort()This method returns the port number of the URL.
8Public int getDefaultPort() This method returns the default port number used by the URL.
9Public String getRef()This method returns the reference to the URL object. The reference is the part represented by ‘#’ in the URL.
10Public String getProtocol()It returns the protocol associated with the URL.

Creating URL With Component Parts

We will learn how to create a URL using URL components such as hostname, filename, and protocol.

Code to Create a URL using URL Components:

package com.techvidvan.urlclass;
import java.net.MalformedURLException;
import java.net.URL;
public class URLClassDemo
{
  public static void main(String[ ] args) throws MalformedURLException
  {
    String protocol = "http";
    String host = "techvidvan.com";
    String file = "/tutorials/java-method-overriding/";
    URL url = new URL(protocol, host, file);
    System.out.println("URL is: " +url.toString());
  }
}

Output:

URL is:
http://techvidvan.com/tutorials/java-method-overriding/
An Example of the URL Class of Java

After looking at the methods and constructors of the URL class in Java, in the following code, we will understand the use of each method of the URL class.

Code to understand URL Class in Java:

package com.techvidvan.urlclass;
import java.net.MalformedURLException;
import java.net.URL;
public class URLClassDemo
{
  public static void main(String[] args) throws MalformedURLException
  {
    URL url1 = new URL("https://techvidvan.com/tutorials/java-polymorphism/");

    System.out.println("url1 is: " +url1.toString());

    System.out.println("\nDifferent components of the url1");
    System.out.println("Protocol: " + url1.getProtocol());
    System.out.println("Hostname: " + url1.getHost());
    System.out.println("Port: " + url1.getPort());
    System.out.println("Default port: " + url1.getDefaultPort());
    System.out.println("Query: " + url1.getQuery());
    System.out.println("Path: " + url1.getPath());
    System.out.println("File: " + url1.getFile());
    System.out.println("Reference: " + url1.getRef());
    System.out.println("Authority: " + url1.getAuthority());

    URL url2 = new URL("https://www.google.com/search?		q=techvidvan&oq=techvidva&aqs=chrome.1.69i57j0.7491j0j7&sourceid=chrome&i		e=UTF-8");

    System.out.println("\nurl2 is: " +url2.toString());

    System.out.println("\nDifferent components of the url2");
    System.out.println("Protocol: " + url2.getProtocol());
    System.out.println("Hostname: " + url2.getHost());
    System.out.println("Port: " + url2.getPort());
    System.out.println("Default port: " + url2.getDefaultPort());
    System.out.println("Query: " + url2.getQuery());
    System.out.println("Path: " + url2.getPath());
    System.out.println("File: " + url2.getFile());
    System.out.println("Reference: " + url2.getRef());
    System.out.println("Authority: " + url2.getAuthority());
  }
}

Output:

url1 is: https://techvidvan.com/tutorials/java-polymorphism/Different components of the url1
Protocol: https
Hostname: techvidvan.com
Port: -1
Default port: 443
Query: null
Path: /tutorials/java-polymorphism/
File: /tutorials/java-polymorphism/
Reference: null
Authority: techvidvan.comurl2 is: https://www.google.com/search?q=techvidvan&oq=techvidva&aqs=chrome.1.69i57j0.7491j0j7&sourceid=chrome&ie=UTF-8

Different components of the url2
Protocol: https
Hostname: www.google.com
Port: -1
Default port: 443
Query: q=techvidvan&oq=techvidva&aqs=chrome.1.69i57j0.7491j0j7&sourceid=chrome&ie=UTF-8
Path: /search
File: /search?q=techvidvan&oq=techvidva&aqs=chrome.1.69i57j0.7491j0j7&sourceid=chrome&ie=UTF-8
Reference: null
Authority: www.google.com

URLConnection Class in Java

The URLConnection class in Java helps to represent a “connection or communication” between the application and the URL. This class also helps us to read and write data to the specified resource of URL.

java.net.URLConnection is an abstract class whose subclasses represent the various types of URL connections.

For example:

  • The openConnection() method returns the object of the HttpURLConnection class if you connect to a URL with the HTTP protocol.
  • Also, this openConnection() method returns the object of a JarURLConnection class if you connect to a URL of a JAR file.
The OpenConnection() Method

We can get the object or instance of the URLConnection class with the open Connection() method of URL class.

Syntax of this method is:

public URLConnection openConnection() throws IOException { }
Methods of URLConnection Class in Java

There are many methods in the URLConnection to set or retrieve the details about the connection. These methods are:

S.N.Method Description
1Object getContent()This method returns the contents of this URL connection.
2String getContentEncoding()This method returns the value of the content-encoding header field in String form.
3int getContentLength()This method gives the value of the content-length header field in the String form.
4String getContentType()This method returns the value of the content-type header field.
5int getLastModified()This method gives the value of the last-modified header field.
6long getExpiration()It returns the value of the expired header field.
7long getIfModifiedSince()This method returns the value of this object’s ifModifiedSince field.
9public void setDoInput(boolean input)We pass the parameter true to this method  to specify that we will use the connection input. 
10public void setDoOutput(boolean output)We pass the parameter true to this method  to specify that we will use the connection output.
11public InputStream getInputStream() throws IOExceptionThis method returns the input stream of the URL connection for reading from the resource.
12public OutputStream getOutputStream() throws IOExceptionIt returns the output stream of the URL connection for writing to the resource.
13public URL getURL()Returns the URL that of this connected URLConnection object.
Example of URLConnection Class

The following URLConnectionDemo class connects to an input URL. If an HTTP resource is present in a URL represents, then connection casts to HttpURLConnection. The data in the resource reads one line at a time.

Code to understand URLConnection class of Java:

package com.techvidvan.urlclass;
import java.net.*;
import java.io.*;
public class URLConnectionDemo
{
  public static void main(String[] args) throws MalformedURLException
  {
    try
    {
      URL url = new URL("https://www.techvidvan.com");
      URLConnection urlConnection = url.openConnection();
      HttpURLConnection connection = null;
      if(urlConnection instanceof HttpURLConnection)
      {
        connection = (HttpURLConnection) urlConnection;
      }
      else
      {
        System.out.println("Please enter an HTTP URL.");
        return;
      }

      BufferedReader in = new BufferedReader(
          new InputStreamReader(connection.getInputStream()));
      String urlString = " ";
      String current;

      while((current = in.readLine()) != null)
      {
        urlString += current;
      }
      System.out.println(urlString);
    } catch (IOException e)
    {
      e.printStackTrace();
    }
  }
}

Output:

…..a complete HTML content of the home page of techvidvan.com…..

Summary

The URL class is used in Java to access network resources programmatically. There are many parts or segments of URL which uniquely identify a URL.

In this tutorial, we learned about the Java URL class in Java along with its constructors and methods. We studied how to create a URL with the help of its components.

There is also a URLConnection class that connects an application with a URL.It also has some methods that we covered in our article. Both URLClass and URLConnection classes are being explained with the example codes in this article.

Thank you for reading our article. Do share this article on Social Media.

Happy Learning 🙂

Your opinion matters
Please write your valuable feedback about TechVidvan on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *