EN
Java - get domain name from given url
3 points
In this article, we would like to show how to get a domain from a given URL in Java.
Quick solution:
xxxxxxxxxx
1
// import java.net.URI;
2
3
String url = "https://dirask.com";
4
5
URI uri = new URI(url);
6
String host = uri.getHost();
7
String domain = host.startsWith("www.") ? host.substring(4) : host;
8
9
System.out.println(domain); // dirask.com
In this section, the code was split to provide reusable DomainUtil
class.
Program.java
file:
xxxxxxxxxx
1
import java.net.URISyntaxException;
2
3
public class Program {
4
5
public static void main(String[] args) throws URISyntaxException {
6
String url = "https://dirask.com/posts/123";
7
String domain = DomainUtil.getDomainName(url);
8
Syste.out.println(domain); // dirask.com
9
}
10
}
Example output:
xxxxxxxxxx
1
dirask.com
DomainUtil.java
file:
xxxxxxxxxx
1
import java.net.URI;
2
import java.net.URISyntaxException;
3
4
public class DomainUtil {
5
6
public static String getDomainName(String url) throws URISyntaxException {
7
URI uri = new URI(url);
8
String host = uri.getHost();
9
return host.startsWith("www.") ? host.substring(4) : host;
10
}
11
}