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.