Learn Java URL Class With Examples

In programming, we frequently need to work with URLs. But what are URLs anyway? Sounds complex. The full form of URL is Uniform Resource Locator.

So from the full form, we can understand that in order to access any resource on the internet we need to have URLs.

But if you see in the address bars of your browsers, you will observe that the URLs are very long strings with random characters and incomprehensible hashes.

However, we do need to parse and extract useful information from URLs in our everyday lives. How do we do that? Java is the answer.

Stay updated with latest technology trends
Join DataFlair on Telegram!!

URL Class in Java

Take an example of the following URL.
https://data-flair.training/

Let us understand what makes up the URL.

A typical URL will consist of a protocol, a hostname, a file name and a port number.

When you look at the URL you will observe that the URL begins with HTTPS.

This is the protocol of connection with the server. There are many protocols, such as HTTP, HTTPS, FTP and so on…

You may read about these protocols later. For now, let us consider a very abstract definition of it.

Let us assume that the protocol is basically a set of rules that the client and the server have to follow in order to transfer data in between them.

The next part of the URL is the domain name. This is basically the name of the website. In our case this is data-flair.training.
This is a unique name given to each website.

Now take a look at this URL right here: https://data-flair.training/blogs/java-tutorial/

The slashes mark directories through which you can find the file you are looking for.

The file name can be any file depending on the website you are visiting. You can choose to open a PHP file, HTML file or a simple “text” file too.

This depends on the webserver entirely.

The port basically indicates what port on the webserver we are connecting to. By default, the web browsers connect to port 80 which is generally configured by a webserver to serve webpages.

Enough about URLs for now.

Let us look at the class java provides us and the constructors we can use!

  1. URL(String address)throws MalFormedException – This constructor takes in a URL and converts it to a URL object for you.
  2. URL(String protocol, String host, String file) – This constructor takes in the protocol, the hostname and the file that we are trying to reach and convert it to a URL object.
  3. URL(String protocol, String host, int port, String file) – This constructor is similar to the previous one. The only additional parameter it takes into account is the port number. You can specify any port number here. This will make a URL object based on the passed parameters.
  4. URL(String protocol, String host, int port, String file, URLStreamHandler handler) – This allows you to specify a handler along with the host, port and the file name.
  5. URL(URL context, String spec, URLStreamHandler handler) – This constructor returns a URL object by parsing the spec with the given handler.

Methods in Java URL Class

Methods in Java URL Class

There are a few methods that we need to learn about before we progress into the programming part.

  • public String toString() – This converts the URL to a string object and returns it. Essential for performing string manipulations on it.
  • public String getAuthority() – This returns the authority of the URL. This basically is a collection of the hostname and the port.
  • public String getPath() – This method returns the URL as a String.
  • public String getQuery() – The query of a URL is the request for a certain type of data in the database. It can also be a specific file in the website directory or a search query.
  • public String getHost() – This returns an IPV6 format of the hostname in the URL.
  • public String getFile() – This method is useful for returning the filename of the resource we are requesting.
  • public int getPort() – This method returns the port coupled with the protocol in the URL. Returns -1 if no value is found.
  • public int getDefaultPort() – This method is useful for returning the default port value.
  • public String getProtocol() – This method is useful for returning the protocol of the URL.
  • public URI toURI() – This method returns a URI of the specified URL.
  • public String getref() – This method is useful for returning the anchor or the reference of the particular URL.
  • public URLConnection OpenConnection() – This function returns an instance of the URLConnection, connected with the particular URL.
  • public Object getContent() – This method is useful for returning the content of the URL. This is returned as an Object.

All the methods which return String return null when no value is found. All the methods which return in ‘int; return -1 when no value can be parsed through the URL.

Enough theory! Let us code an example and see how it looks.

Java program to illustrate the methods of the URL class:

package com.dataflair.javaurl;
import java.net.*;
public class TestURL
{
    public static void main(String[] args)throws Exception{
        String url="https://data-flair.training/blogs/java-tutorial/";


        URL testurl= new URL(url);
        System.out.println("The string representation of the URL -> "+testurl.toString());
        System.out.println("The Authority of the URL -> "+testurl.getAuthority());
        System.out.println("The Path of the URL -> "+testurl.getPath());
        System.out.println("The Query of the URL -> "+testurl.getQuery());
        System.out.println("The host of the URL -> "+testurl.getHost());
        System.out.println("The file of the URL -> "+testurl.getFile());
        System.out.println("The port of the URL -> "+testurl.getPort());
        System.out.println("The default port of the URL -> "+testurl.getDefaultPort());
        System.out.println("The protocol of the URL -> "+testurl.getProtocol());
        
        
        System.out.println("The results are null or -1 in some cases because no particular values could not be parsed");

    }
}

Output:

The string representation of the URL -> https://data-flair.training/blogs/java-tutorial/
The Authority of the URL -> data-flair.training
The Path of the URL -> /blogs/java-tutorial/
The Query of the URL -> null
The host of the URL -> data-flair.training
The file of the URL -> /blogs/java-tutorial/
The port of the URL -> -1
The default port of the URL -> 443
The protocol of the URL -> https
The results are null or -1 in some cases because no particular values could not be parsed

Summary

We have reached the end of another interesting article. We learned about the different methods that the URL class in java provides us.

More complex URLs are easily parsable by these methods. In Networking applications, it is essential for a programmer to use these methods.

Can you imagine the inconvenience we would have faced if there weren’t any inbuilt URL parsing methods in Java? We had to hard code each and every method from the ground up. That would lead to confusion and errors.

That is exactly why the URL class is a favourite for almost every Java Developer out there.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google | Facebook

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.