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.
The getHost() method of URL class returns the hostname of the URL. This method will return the IPv6 address enclosed in square brackets ('['and']').
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));
The hostname property of the URL interface is a string containing the domain name of the URL.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With