The Wayback Machine - https://web.archive.org/web/20240608120625/https://www.geeksforgeeks.org/url-class-java-examples/
Open In App

URL Class in Java with Examples

Last Updated : 18 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

URL known as Uniform Resource Locator is simply a string of text that identifies all the resources on the Internet, telling us the address of the resource, how to communicate with it, and retrieve something from it.

URL Class

Components of a URL

A URL can have many forms. The most general however follows a three-components system as proposed below:

  1. Protocol: HTTP is the protocol here
  2. Hostname: Name of the machine on which the resource lives.
  3. File Name: The pathname to the file on the machine.
  4. Port Number: Port number to which to connect (typically optional).

URL Class 

The URL class is the gateway to any of the resources available on the internet. A Class URL represents a Uniform Resource Locator, which is a pointer to a “resource” on the World Wide Web. A resource can point to a simple file or directory, or it can refer to a more complicated object, such as a query to a database or to a search engine.

Constructors of the URL class

  1. URL(String address) throws MalformedURLException: It creates a URL object from the specified String.
  2. URL(String protocol, String host, String file): Creates a URL object from the specified protocol, host, and file name.
  3. URL(String protocol, String host, int port, String file): Creates a URL object from protocol, host, port, and file name.
  4. URL(URL context, String spec): Creates a URL object by parsing the given spec in the given context. 
  5. URL(String protocol, String host, int port, String file, URLStreamHandler handler):
    Creates a URL object from the specified protocol, host, port number, file, and handler.
  6. URL(URL context, String spec, URLStreamHandler handler):
    Creates a URL by parsing the given spec with the specified handler within a specified context.

Important Methods used in URL class

Method Action Performed
getAuthority() Returns the authority part of URL or null if empty
getDefaultPort() Returns the default port used
getFile() Returns the file name.
getHost() Return the hostname of the URL in IPv6 format
getPath() Returns the path of the URL, or null if empty
getPort() Returns the port associated with the protocol specified by the URL
getProtocol() Returns the protocol used by the URL
getQuery() the Returns the query part of URL. A query is a part after the ‘?’ in the URL. Whenever logic is used to display the result, there would be a query field in the URL. It is similar to querying a database.
getRef() Returns the reference of the URL object. Usually, the reference is the part marked by a ‘#’ in the URL. You can see the working example by querying anything on Google and seeing the part after ‘#’
toString() As in any class, toString() returns the string representation of the given URL object.

Example:

Java




// Java program to demonstrate working of URL
  
// Importing required classes
import java.net.MalformedURLException;
import java.net.URL;
  
// Main class
// URL class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
        throws MalformedURLException
    {
  
        // Creating a URL with string representation
        URL url1 = new URL(
            + "WK26I4fT8gfth6CACg#q=geeks+for+geeks+java");
  
        // Creating a URL with a protocol,hostname,and path
        URL url2 = new URL("http", "www.geeksforgeeks.org",
                           "/jvm-works-jvm-architecture/");
  
        URL url3 = new URL(
            "https://www.google.co.in/search?"
            + "q=gnu&rlz;=1C1CHZL_enIN71"
            + "4IN715&oq;=gnu&aqs;=chrome..69i57j6"
            + "9i60l5.653j0j7&sourceid;=chrome&ie;=UTF"
            + "-8#q=geeks+for+geeks+java");
  
        // Printing the string representation of the URL
        System.out.println(url1.toString());
        System.out.println(url2.toString());
        System.out.println();
        System.out.println(
            "Different components of the URL3-");
  
        // Retrieving the protocol for the URL
        System.out.println("Protocol:- "
                           + url3.getProtocol());
  
        // Retrieving the hostname of the url
        System.out.println("Hostname:- " + url3.getHost());
  
        // Retrieving the default port
        System.out.println("Default port:- "
                           + url3.getDefaultPort());
  
        // Retrieving the query part of URL
        System.out.println("Query:- " + url3.getQuery());
  
        // Retrieving the path of URL
        System.out.println("Path:- " + url3.getPath());
  
        // Retrieving the file name
        System.out.println("File:- " + url3.getFile());
  
        // Retrieving the reference
        System.out.println("Reference:- " + url3.getRef());
    }
}


Output:  

https://www.google.co.in/?gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q=geeks+for+geeks+java
https://www.geeksforgeeks.org/jvm-works-jvm-architecture/

Different components of the URL3-
Protocol:- https
Hostname:- www.google.co.in
Default port:- 443
Query:- q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8
Path:- /search
File:- /search?q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8
Reference:- q=geeks+for+geeks+java

 



Previous Article
Next Article

Similar Reads

java.net.URL Class in Java
URL is an acronym of Uniform resource locator. It is a pointer to locate resource in www (World Wide Web). A resource can be anything from a simple text file to any other like images, file directory etc. The typical URL may look like http://www.example.com:80/index.htmlThe URL has the following parts: Protocol: In this case the protocol is HTTP, It
4 min read
URL sameFile() method in Java with Examples
The sameFile() function of Java.net.URL class is used to compare two URLs excluding the fragment part. This method returns true if both the URL are same excluding the fragment part else returns false. Function Signature public boolean sameFile(URL u) Syntax url1.sameFile(url2); Parameter: This method accepts a mandatory parameter url which is the s
2 min read
URL getDefaultPort() method in Java with Examples
The getDefaultPort() function of URL class returns the default port of a specified URL. If the URL scheme or the URLStreamHandler for the URL do not define a default port number then the function returns -1. Function Signature public int getDefaultPort() Syntax url.getDefaultPort() Parameter This function does not require any parameter Return Value
2 min read
URL toURI() method in Java with Examples
The getURI() function of URL class converts the URL object to a URI object. Any URL which compiles with RFC 2396 can be converted to URI. URLs which are not in the specified format will generate an error if converted to URI format. Function Signature public URI toURI() Syntax url.toURI() Parameter: This method do not accept any parameter. Return ty
2 min read
URL getHost() method in Java with Examples
getHost() function is a part of URL class. The function getHost() returns the Host of a specified URL. The Host part of the URL is the host name of the URL. The format of the host conforms to RFC 2732. Function Signature public String getHost() Syntax url.getHost() Parameter: This function does not require any parameter Return Type: The function re
2 min read
URL getAuthority() method in Java with Examples
The getAuthority() function is a part of URL class. The function getAuthority() returns the authority of a specified URL. The Authority part of the URL is the host name and the port of the URL. Function Signature public String getAuthority() Syntax url.getAuthority() Parameter: This function does not require any parameter Return Type: The function
2 min read
URL getPort() method in Java with Examples
The getPort() function is a part of URL class. The function getPort() returns the port of a specified URL. The function returns the port number or -1 if the port is not set Function Signature public int getPort() Syntax url.getPort() Return Type: The function returns Integer Type Parameter: This function does not require any parameter Below program
2 min read
URL getProtocol() method in Java with Examples
The getProtocol() function is a part of URL class. The function getProtocol() returns the Protocol of a specified URL. Function Signature public String getProtocol() Syntax url.getProtocol() Parameter This function does not require any parameter Return Type: The function returns String Type Below programs illustrates the use of getProtocol() functi
2 min read
URL getQuery() method in Java with Examples
The getQuery() function is a part of URL class. The function getQuery() returns the Query of a specified URL. Function Signature: public String getQuery() Syntax: url.getQuery() Parameter: This function does not require any parameter Return Type: The function returns String Type Query of a specified URL. Below programs illustrates the use of getQue
2 min read
URL getUserInfo() method in Java with Examples
The getUserInfo() function is a part of URL class. The function getUserInfo() returns the UserInfo part of a specified URL. Function Signature: public String getUserInfo() Syntax: url.getUserInfo() Parameter: This function does not require any parameter Return Type: The function returns String Type Below programs illustrates the use of getUserInfo(
2 min read
Article Tags :
Practice Tags :