Java URL Class


The java.net.URL class serves as a representation for Uniform Resource Locators that identify web resources such as files, webpages, or data streams.

 

The URL class enables both content reading from web addresses and metadata extraction which includes protocol information and host details.


Syntax

Creating a URL Object

URL url = new URL("https://www.example.com");

 

You can also create using individual parts:

URL url = new URL("https", "www.example.com", "/index.html");

Methods

Method Description
getProtocol() Returns the protocol (http, https, ftp, etc.)
getHost() Returns the domain name
getPort() Returns the port number (-1 if not set)
getPath() Returns the file path
getQuery() Returns the query string
openStream() Opens a stream for reading content
toURI() Converts the URL to a URI

Example

 import java.io.*;
import java.net.*;

public class URLReadExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.onlinetpoint.com");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }

            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Example: Accessing URL Parts

 import java.net.*;

public class URLPartsExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://www.onlinetpoint.com:443/path/index.html?name=java");

        System.out.println("Protocol: " + url.getProtocol());
        System.out.println("Host: " + url.getHost());
        System.out.println("Port: " + url.getPort());
        System.out.println("Path: " + url.getPath());
        System.out.println("Query: " + url.getQuery());
    }
}

Output

Protocol: https
Host: www.onlinetpoint.com
Port: 443
Path: /path/index.html
Query: name=java



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.