Languages
[Edit]
EN

Java - get domain name from given url

3 points
Created by:
Abul-Emery
457

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

Quick solution:

// import java.net.URI;

String url = "https://dirask.com";

URI uri = new URI(url);
String host = uri.getHost();
String domain = host.startsWith("www.") ? host.substring(4) : host;

System.out.println(domain);  // dirask.com

 

Practical example

In this section, the code was split to provide reusable DomainUtil class.

Program.java file:

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
    }
}

Example output:

dirask.com

 

DomainUtil.java file:

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 host = uri.getHost();
        return host.startsWith("www.") ? host.substring(4) : host;
    }
}
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join