Sunday, October 16, 2011

Get Domain Name from a URL String in Java

To get the domain name or sub-domain name from a URL String in Java we can use the java.net.URL object. First a URL object is created, passing the URL String to its constructor. If the URL String is malformed or invalid, a MalformedURLException will be thrown. The getHost() method is then used to pull only the part of the URL containing the domain name. The following code demonstrates getting the domain name from a URL String.


import java.net.MalformedURLException;
import java.net.URL;

//
// The following example code demonstrates how to
// get the domain name from a URL String
//
public class GetDomainNameFromURL {

    public static void main(String[] args) throws MalformedURLException {

        String testURLString = "https://thermodynamiccomputing.com/main?&t=20&f=52";
        URL lURL = new URL(testURLString);
        String hostName = lURL.getHost();
        System.out.println(hostName);

        testURLString = "http://www.thermodynamiccomputing.com/main?&t=20&f=52";
        lURL = new URL(testURLString);
        hostName = lURL.getHost();
        System.out.println(hostName);

        testURLString = "http://www.sub.thermodynamiccomputing.com/main?&t=20&f=52";
        lURL = new URL(testURLString);
        hostName = lURL.getHost();
        System.out.println(hostName);

    }
}



Here is the output of the example code:
thermodynamiccomputing.com
www.thermodynamiccomputing.com
www.sub.thermodynamiccomputing.com
Piece of cake!!!

No comments: