A domain is a human-readable identifier that represents a specific web location. Usually, we extract the domain names from the URL for analytics or to provide personalization services. In this article, we will see how to extract a domain name from a URL using Java.
Generally, the URL contains several components, including the protocol, domain name, path, query parameters, and many more. To extract the domain name from the URL, we use java’s URI class.
Extracting the domain name from the URL using Java’s URI class
URI class provides several methods to extract the domain name from the URL. Following is an example:
import java.net.URI;
import java.net.URISyntaxException;
public class DomainNameExtractor {
public static String extractDomainName(String url) {
try {
URI uri = new URI(url);
String domain = uri.getHost();
if (domain != null) {
return domain.startsWith("www.") ? domain.substring(4) : domain;
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String url = "https://www.name.com/resource";
String domainName = extractDomainName(url);
System.out.println("Domain Name: " + domainName);
}
}
Explanation:
In the above example, the extractDomainName()
method takes the URL as an input and uses the java.net.URI
class to extract the domain name from it.
Theuri.getHost()
method extracts the host (domain name) from the URL. If the domain name starts with “www.”, we are removing it for consistency.