Java URL to Host Name getHost(String url)

Here you can find the source of getHost(String url)

Description

get Host

License

Open Source License

Declaration

public static String getHost(String url) 

Method Source Code

//package com.java2s;
/******************************************************************************* 
 * Copyright (c) 2012-2016 Red Hat, Inc. 
 * Distributed under license by Red Hat, Inc. All rights reserved. 
 * This program is made available under the terms of the 
 * Eclipse Public License v1.0 which accompanies this distribution, 
 * and is available at http://www.eclipse.org/legal/epl-v10.html 
 * //from w  w w. j av  a2  s.c o m
 * Contributors: 
 * Red Hat, Inc. - initial API and implementation 
 ******************************************************************************/

import java.net.URI;
import java.net.URISyntaxException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static final String SCHEME_SEPARATOR = "://";
    private static final Pattern SIMPLE_QUASI_URL_PATTERN = Pattern
            .compile("^((\\w+:/)?(/*)?(.*@)?)([^:|/]*)(.*)?$");

    public static String getHost(String url) {
        if (isEmpty(url)) {
            return url;
        }
        String host = null;
        if (url.contains(SCHEME_SEPARATOR)) {
            try {
                host = new URI(url).getHost();
            } catch (URISyntaxException ignored) {
            }
        }

        if (host == null) {
            Matcher m = SIMPLE_QUASI_URL_PATTERN.matcher(url);
            if (m.find()) {
                host = m.group(5);
            }
        }
        return host;
    }

    private static boolean isEmpty(String string) {
        return string == null || string.isEmpty();
    }
}

Related

  1. getHost(String url)
  2. getHost(String url)
  3. getHost(String url)
  4. getHost(String url)
  5. getHost(String urlString)
  6. getHost(String urlString)
  7. getHost(URL url)