Java program to get domain name by URL

We can also get the domain name by the java program.
Domain name are used to represent the symbolic representation of numerical
internet address.
In our this example to get the domain name we have used
an URL for getting the domain name.
String urlAddress = "http://www.roseindia.net/jsf/JSFLoginApplication.shtml";
URL url = new URL(urlAddress);
In above lines of code we have created an object of URL
class which consists an internet address. Now we can get the domain name by
using the method getHost() on the object of URL.
url.getHost() returns the domain name for
the given URL address.Here is the example code of GetDomainName.java
as follows:
GetDomainName.java
import java.util.*;
import java.lang.*;
import java.net.*;
public class GetDomainName
{
public static void main(String args[]) {
try{
String urlAddress = "http://www.roseindia.net/jsf/JSFLoginApplication.shtml";
URL url = new URL(urlAddress);
String domain = url.getHost();
System.out.println("Domain name by URL
\"http://www.roseindia.net/jsf/JSFLoginApplication.shtml \" is :"
+ domain);
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
}
}
}
|
Output:
C:\javaexamples>javac GetDomainName.java
C:\javaexamples>java GetDomainName
Domain name by URL "http://www.roseindia.net/jsf/JSFLoginApplication.shtml " is :www.roseindia.net |
Download Source Code

|