Java URL to Host Name getHost(String urlString)

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

Description

Retrieves the host from a URL {Category} StringUtil {param} string(url) url: String.

License

Apache License

Declaration

public static String getHost(String urlString) 

Method Source Code

//package com.java2s;
/**//from w ww  .  j  a va 2  s.com
 * Copyright 2015 Jan Lolling jan.lolling@gmail.com
 * 
 * Licensed 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.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

public class Main {
    /**
     * Retrieves the host from a URL
     * 
     * {Category} StringUtil
     * 
     * {param} string(url) url: String.
     * 
     * {example} getHost(url) # DE
     */
    public static String getHost(String urlString) {
        if (urlString == null) {
            return null;
        }
        urlString = urlString.trim().toLowerCase();
        if (urlString.startsWith("http://") == false) {
            urlString = "http://" + urlString;
        }
        String decUrl = null;
        try {
            decUrl = java.net.URLDecoder.decode(urlString, "ASCII");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("getHost failed: " + e.getMessage(),
                    e);
        }
        java.net.URL url = null;
        try {
            url = new java.net.URL(decUrl);
        } catch (MalformedURLException e) {
            throw new RuntimeException("getHost failed: " + e.getMessage(),
                    e);
        }
        return url.getHost();
    }

    /**
     * returns the lower case string, is null save
     * 
     * {Category} StringUtil
     * 
     * {param} string(input) input: String.
     * 
     * {example} toLowerCase("AbC") # "abc"
     */
    public static String toLowerCase(String input) {
        if (input == null) {
            return null;
        } else {
            return input.toLowerCase();
        }
    }
}

Related

  1. getHost(String url)
  2. getHost(String url)
  3. getHost(String url)
  4. getHost(String url)
  5. getHost(String url)
  6. getHost(String urlString)
  7. getHost(URL url)
  8. getHostAddressAsBytes(String url)
  9. getHostAndPort(final URL url)