Java URL to Host Name getHost(String url)

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

Description

get Host

License

Apache License

Declaration

public static String getHost(String url) 

Method Source Code

//package com.java2s;
/*// w w w .  j ava 2s  .  c o m
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

public class Main {
    public static String getHost(String url) {
        //return InternetDomainName.from(url).topPrivateDomain().toString();
        /*if () {
        return InternetDomainName.from(url).topPrivateDomain().toString();
        } else {
        System.out.println("Omg, It's not a valid URL: " + url);
        return "";
        }*/

        URI uri = null;
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            System.out.println("Omg, It's not a valid URL: " + url);
            // Do Nothing & Return Empty ""
            return "";
        }
        String host = uri.getHost();
        if (host != null) {
            if (host.startsWith("www.")) {
                return host.substring(4);
            } else {
                return host;
            }
        } else {
            System.out.println("Omg, www not present: " + url);
            return "";
        }
    }
}

Related

  1. getHost(String url)
  2. getHost(String url)
  3. getHost(String url)
  4. getHost(String url)