get Domain From Url - Java Network

Java examples for Network:URL

Description

get Domain From Url

Demo Code


//package com.java2s;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

public class Main {
    public static String getDomainFromUrl(String url) {
        if (url == null || !isValidUrl(url))
            return "";
        return url.split("//")[1].split("/")[0];
    }/*  w w w.  ja v a2s. c o m*/

    public static boolean isValidUrl(String url) {
        if (url == null || url.length() == 0)
            return false;

        /*
         * from stackoverflow:
         * http://stackoverflow.com/questions/1600291/validating-url-in-java
         */
        URL u = null;

        try {
            u = new URL(url);
        } catch (MalformedURLException e) {
            return false;
        }

        try {
            u.toURI();
        } catch (URISyntaxException e) {
            return false;
        }

        return true;
    }
}

Related Tutorials