Extract host name/domain name from URL string

java.net.URL u = new URL("http://hostname:port_no/control/login.jsp");
System.err.println(u.getHost());

java.net.URL aURL;
try {
    aURL = new java.net.URL("http://example.com:80/docs/");
    System.out.println("host = " + aURL.getHost()); //example.com
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

You can use the java.net.URI-class to extract the hostname from the string.

Here below is a method from which you can extract your hostname from a string.

public String getHostName(String url) {
    URI uri = new URI(url);
    String hostname = uri.getHost();
    // to provide faultproof result, check if not null then return only hostname, without www.
    if (hostname != null) {
        return hostname.startsWith("www.") ? hostname.substring(4) : hostname;
    }
    return hostname;
}

This above gives you the hostname, and is faultproof if your hostname does start with either hostname.com/... or www.hostname.com/..., which will return with 'hostname'.

If the given url is invalid (undefined hostname), it returns with null.

Tags:

Java

String

Url