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.
@KarelG's answer is the best answer, though I had specific issues with certain non-standard domains. The example issue is self contained below.
For certain "real world" input values, I had to add a check to the URI scheme to avoid mis-parsing of some addresses. This is the changed code.
Below is the test case and value that was failing.
Domain.java javac Domain.java java Domain
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.
This above gives you the hostname, and is faultproof if your hostname does start with either
hostname.com/...
orwww.hostname.com/...
, which will return with 'hostname'.If the given
url
is invalid (undefined hostname), it returns with null.If you want string work, then try the following code sample,
In Java:
Hope this helps.