Java URI to Host Name getHost(final URI uri)

Here you can find the source of getHost(final URI uri)

Description

Return just the host portion of the URI if applicable.

License

Open Source License

Parameter

Parameter Description
uri The URI to parse

Return

The host portion of the authority.

Declaration

public static String getHost(final URI uri) 

Method Source Code

//package com.java2s;
/*// w  w  w.  j  av  a2s.  c  om
 * Copyright (c) 2014 Stephan D. Cote' - All rights reserved.
 * 
 * This program and the accompanying materials are made available under the 
 * terms of the MIT License which accompanies this distribution, and is 
 * available at http://creativecommons.org/licenses/MIT/
 *
 * Contributors:
 *   Stephan D. Cote 
 *      - Initial concept and implementation
 */

import java.net.URI;

public class Main {
    /**
     * Return just the host portion of the URI if applicable.
     *
     * @param uri The URI to parse
     * 
     * @return The host portion of the authority.
     */
    public static String getHost(final URI uri) {
        String retval = uri.getHost();

        // The most common reason for getHost failure is that a port was not
        // defined in the URI making it hard for the URI class to figure out which
        // part of the authority is the host portion. We assume anything infront of
        // the colon is the host.
        if ((retval == null) && (uri.getAuthority() != null)) {
            // The authority is usually in the form of XXXX:999 as in "myhost:-1"
            final String text = uri.getAuthority();
            final int ptr = text.indexOf(':');

            if (ptr > -1) {
                // just return the host portion
                retval = text.substring(0, ptr);
            }
        }

        return retval;
    }
}

Related

  1. getHost(URI uri)
  2. getHost(URI uri)
  3. getHost(URI uri)
  4. getHostAddress(final URI uri)