Java HTTP Port Find getCorrectHostnamePort(String hostPort)

Here you can find the source of getCorrectHostnamePort(String hostPort)

Description

Method to validate if the given String represents a hostname:port.

License

Apache License

Return

URL object for accessing host and Port

Declaration

public static URL getCorrectHostnamePort(String hostPort) 

Method Source Code

//package com.java2s;
/*/*from  ww w .j  a  v  a2  s.  com*/
 * 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.MalformedURLException;

import java.net.URL;

public class Main {
    /**
     * Method to validate if the given String represents a hostname:port.
     *
     * Works also for ipv6.
     *
     * See: http://stackoverflow.com/questions/2345063/java-common-way-to-validate-and-convert-hostport-to-inetsocketaddress
     *
     * @return URL object for accessing host and Port
     */
    public static URL getCorrectHostnamePort(String hostPort) {
        try {
            URL u = new URL("http://" + hostPort);
            if (u.getHost() == null) {
                throw new IllegalArgumentException(
                        "The given host:port ('" + hostPort + "') doesn't contain a valid host");
            }
            if (u.getPort() == -1) {
                throw new IllegalArgumentException(
                        "The given host:port ('" + hostPort + "') doesn't contain a valid port");
            }
            return u;
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("The given host:port ('" + hostPort + "') is invalid", e);
        }
    }
}

Related

  1. getAvailablePort(int startPort)
  2. getAvailablePort(String hostname, String portRange)
  3. getAvailablePorts(int basePort, int portCount)
  4. getAvailablePortsFromRange(int portMin, int portMax, int numberOfPorts)
  5. getAvialablePort(final int basePort)
  6. getEffectivePort(String scheme, int specifiedPort)
  7. getEphemeralPort()
  8. getFreeLocalPort()
  9. getFreePort()