Extracting Protocol and Domain from a URL in Java

The java.net.URL class can parse a URL string and expose its components. To obtain the portocol and host, create a URL instanec and call getProtocol() and getHost().

import java.net.URL;

public class UrlParser {
    public static void main(String[] args) throws Exception {
        URL endpoint = new URL("https://docs.oracle.com/en/java/");
        
        String scheme = endpoint.getProtocol();
        String host = endpoint.getHost();
        
        System.out.println("Scheme: " + scheme);
        System.out.println("Host: " + host);
    }
}
  • getProtocol() returns the protocol (e.g., "https").
  • getHost() returns the host name (e.g., "docs.oracle.com"). It does not include the port.

Both methods can throw a NullPointerException if the URL was created from a string without a protocol or host component. To handle malformed URLs, wrap the new URL(...) call in a try-catch block for MalformedURLException.

Tags: java URL networking parsing protocol

Posted on Thu, 10 Sep 2026 16:47:59 +0000 by fry2010