The URL class in the java.net package represents a Uniform Resource Locator, which identifies the location of a resource on the internet. It provides methods to access URL components and open a connection to the resource.
Provides access to components such as the protocol, host, port, path, and query.
Enables connections to resources through supported protocols, such as HTTP, HTTPS, and FTP.
Components of a URL
A URL can have many forms. The most general however follows a three-component system as proposed below:
Its main components are:
Component
Example
Description
Protocol/Scheme
https
Specifies how the resource is accessed
Host
www.example.com
Identifies the server that hosts the resource
Port
443
Identifies the network port used for communication
Path
/products/search
Identifies the resource location on the server
Query
q=java
Contains parameters passed after ?
Fragment
results
Identifies a specific section after
URL Class
The URL class is a core Java networking class used to access internet-based resources.
It can point to static files, dynamic content, and APIs
Provides constructors to create URL objects
Offers methods to extract different parts of a URL
Constructors of URL class
1. URL(String address): It creates a URL object from the specified String.
URL url = new URL("https://www.example.com/");
2. URL(String protocol, String host, String file): Creates a URL object from the specified protocol, host, and file name.
URL url = new URL("http", "www.example.com", "/path/to/resource");
3. URL(String protocol, String host, int port, String file): Creates a URL object from protocol, host, port, and file name.
URL url = new URL("https", "www.example.com", 443, "/path/to/resource");
4. URL(URL context, String spec): Creates a URL object by parsing the given spec in the given context.
URL baseUrl = new URL("https://www.example.com/"); URL relativeUrl = new URL(baseUrl, "/path/to/resource");
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.
URL url = new URL("http", "www.example.com", 80, "/path/to/resource", new MyCustomHandler());
6. URL(URL context, String spec, URLStreamHandler handler): Creates a URL by parsing the given spec with the specified handler within a specified context.
URL baseUrl = new URL("https://www.example.com/"); URL relativeUrl = new URL(baseUrl, "/path/to/resource", new MyCustomHandler());
Example: Program to demonstrate the working of URL.
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.
You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.