Languages
[Edit]
EN

Java - get domain name from given url

3 points
Created by:
AnnLen
8880

In this article we would like to show how to get domain from given URL in Java.

Simple solution:

import java.net.URI;
import java.net.URISyntaxException;

public class DomainUtil {

    public static String getDomainName(String url) throws URISyntaxException {
        URI uri = new URI(url);
        String domain = uri.getHost();
        return domain.startsWith("www.") ? domain.substring(4) : domain;
    }
}

Usage example:

import java.net.URISyntaxException;

public class Program {

    public static void main(String[] args) throws URISyntaxException {
        String url = "https://dirask.com/posts/123";
        String domain = DomainUtil.getDomainName(url);
        Syste.out.println(domain); // dirask.com
    }
}

Output:

dirask.com

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join