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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.