Java URL to Host Name getHostSegments(URL url)

Here you can find the source of getHostSegments(URL url)

Description

Partitions of the hostname of the url by "."

License

Apache License

Declaration

public static String[] getHostSegments(URL url) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

import java.util.regex.Pattern;

public class Main {
    private static Pattern IP_PATTERN = Pattern.compile("(\\d{1,3}\\.){3}(\\d{1,3})");

    /** Partitions of the hostname of the url by "."  */
    public static String[] getHostSegments(URL url) {
        String host = url.getHost();
        // return whole hostname, if it is an ipv4
        // TODO : handle ipv6
        if (IP_PATTERN.matcher(host).matches())
            return new String[] { host };
        return host.split("\\.");
    }//from  w w  w . ja  va  2 s  .  co  m

    /** Partitions of the hostname of the url by "."
     * @throws MalformedURLException */
    public static String[] getHostSegments(String url) throws MalformedURLException {
        return getHostSegments(new URL(url));
    }

    /**
     * Returns the lowercased hostname for the url or null if the url is not well
     * formed.
     * 
     * @param url The url to check.
     * @return String The hostname for the url.
     */
    public static String getHost(String url) {
        try {
            return new URL(url).getHost().toLowerCase();
        } catch (MalformedURLException e) {
            return null;
        }
    }
}

Related

  1. getHostName(String url)
  2. getHostName(String url)
  3. getHostName(String url)
  4. getHostName(String url)
  5. getHostname(String urlStr)