URL class in Java is a part of java.net package that makes it easy to work with Uniform Resource Locators (URLs). URL 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. This article covers the key components, classes, constructors, methods, and examples of using the URL class in Java applications.
Components of a URL
A URL can have many forms. The most general however follows a three-component system as proposed below:
- Protocol: "http" is the protocol here.
- Host Machine: Name of the machine on which the resource lives (www.geeksforgeeks.org)
- File Name: The pathname to the file on the machine.
- Port Number: Port number to which to connect (typically optional).
URL Class
- The
URL class in Java is a fundamental component for accessing resources on the internet - The URL can point to various types of resources such as static files, dynamic content, API's.
- The
URL class provides constructors and methods to create URL objects and retrieve their components.
Constructors of URL class
1. URL(String address): It creates a URL object from the specified String.
Example:
try {
URL url = new URL("https://www.example.com/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
2. URL(String protocol, String host, String file): Creates a URL object from the specified protocol, host, and file name.
Example:
try {
URL url = new URL("http", "www.example.com", "/path/to/resource");
} catch (MalformedURLException e) {
e.printStackTrace();
}
3. URL(String protocol, String host, int port, String file): Creates a URL object from protocol, host, port, and file name.
Example:
try {
URL url = new URL("https", "www.example.com", 443, "/path/to/resource");
} catch (MalformedURLException e) {
e.printStackTrace();
}
4. URL(URL context, String spec): Creates a URL object by parsing the given spec in the given context.
Example:
try {
URL baseUrl = new URL("https://www.example.com/");
URL relativeUrl = new URL(baseUrl, "/path/to/resource");
} catch (MalformedURLException e) {
e.printStackTrace();
}
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.
Example:
try {
URL url = new URL("http", "www.example.com", 80, "/path/to/resource", new MyCustomHandler());
} catch (MalformedURLException e) {
e.printStackTrace();
}
6. URL(URL context, String spec, URLStreamHandler handler): Creates a URL by parsing the given spec with the specified handler within a specified context.
Example:
try {
URL baseUrl = new URL("https://www.example.com/");
URL relativeUrl = new URL(baseUrl, "/path/to/resource", new MyCustomHandler());
} catch (MalformedURLException e) {
e.printStackTrace();
}
Java URL Methods
| Method | Description |
|---|
| 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() | Return the query part of the URL, which is the portion following the ? character, used to pass parameters to a web application. |
| getRef() | Return the reference part of the URL, which is the portion following the # character, typically used to navigate to a specific section within a web page. |
| toString() | As in any class, toString() returns the string representation of the given URL object. |
Example: The below Java program demonstrate the working of URL.
Java
// Java program to demonstrate working of URL
import java.net.MalformedURLException;
import java.net.URL;
public class Geeks {
public static void main(String[] args)
throws MalformedURLException
{
// Creating a URL with string representation
URL u1 = new URL(
"https://www.google.co.in/?gfe_rd=cr&ei=ptYq"
+ "WK26I4fT8gfth6CACg#q=geeks+for+geeks+java");
// Creating a URL with a protocol, hostname, and
// path
URL u2 = new URL("http", "www.geeksforgeeks.org",
"/jvm-works-jvm-architecture/");
URL u3 = new URL(
"https://www.google.co.in/search"
+ "q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8#q=geeks+for+geeks+java");
// Printing the string representation of the URL
System.out.println(u1.toString());
System.out.println(u2.toString());
System.out.println();
System.out.println("Different components of URL3:");
// Retrieving the protocol for the URL
System.out.println("Protocol: " + u3.getProtocol());
// Retrieving the hostname of the URL
System.out.println("Hostname: " + u3.getHost());
// Retrieving the default port
System.out.println("Default port: "
+ u3.getDefaultPort());
// Retrieving the query part of the URL
System.out.println("Query: " + u3.getQuery());
// Retrieving the path of the URL
System.out.println("Path: " + u3.getPath());
// Retrieving the file name
System.out.println("File: " + u3.getFile());
// Retrieving the reference
System.out.println("Reference: " + u3.getRef());
}
}
Output:
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java In Java, an array is an important linear data structure that allows us to store multiple values of the same type. Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the java.lang.Object class. This allows you to invoke methods defined in Object (such as toStri
9 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
9 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Introduction to Java Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read