Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract host name/domain name from URL string

Tags:

java

string

url

I have a URL like http://hostname:port_no/control/login.jsp.

I have the above url stored in some String.Now, I need to extract hostname from the String.

I am doing like this in my Java code

String domain = url.substring(url.indexOf('/') + 2, url.lastIndexOf(':'));

I want to know if there is any better way to do the same.

like image 243
Anand Avatar asked Apr 15 '14 09:04

Anand


People also ask

How do I find the hostname of a URL?

The getHost() method of URL class returns the hostname of the URL. This method will return the IPv6 address enclosed in square brackets ('['and']').

How do I find the domain of a string?

First let's create a string with our URL (Note: If the URL isn't correctly structured you'll get an error). const url = 'https://www.michaelburrows.xyz/blog?search=hello&world'; Next we create a URL object using the new URL() constructor. let domain = (new URL(url));

What is hostname in URL example?

The hostname property of the URL interface is a string containing the domain name of the URL.


1 Answers

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.

like image 181
KarelG Avatar answered Sep 20 '22 14:09

KarelG