Java Utililty Methods HTTP Port Find

List of utility methods to do HTTP Port Find

Description

The list of methods to do HTTP Port Find are organized into topic(s).

Method

intfreePort()
Retrieve a free port on the current system.
final ServerSocket server = new ServerSocket(0);
try {
    return server.getLocalPort();
} finally {
    server.close();
intfreePort(int suggestedPort)
Returns a free port number at/above suggestedPort.
while (!available(suggestedPort)) {
    suggestedPort++;
return suggestedPort;
Stringget(int port, String applicationRoot, String resource, String path)
get
String url = "http://localhost:" + port + applicationRoot + resource + path;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
...
HashSetgetAllHostNames(String hostName, int portNumber, String bindingUser)
get All Host Names
HashSet obj = new HashSet();
StringTokenizer tokenStr = new StringTokenizer(hostName);
while (tokenStr.hasMoreTokens()) {
    String key = tokenStr.nextToken().trim();
    if (key.indexOf(":") > 0) {
        key = key.substring(0, key.indexOf(":")) + ":" + portNumber + ":" + bindingUser;
    } else {
        key = key + ":" + portNumber + ":" + bindingUser;
...
intgetAnonymousPort()
Get an anonymous socket port.
java.net.ServerSocket socket = new java.net.ServerSocket(0);
int port = socket.getLocalPort();
socket.close();
return port;
StringgetAnonymousPort()
Get an anonymous port
return String.valueOf(getPort(0));
intgetAvailableListenPort()
A helper method to get a random free port.
for (int i = 0; i < MAX_PORT_COUNT; i++) {
    int candidatePort = BASE_PORT + NEXT_PORT.getAndIncrement() % MAX_PORT_COUNT;
    try {
        ServerSocket serverSocket = new ServerSocket(candidatePort);
        serverSocket.close();
        return candidatePort;
    } catch (IOException e) {
throw new IllegalStateException(
        String.format("Could not assign port in range %d - %d", BASE_PORT, MAX_PORT_COUNT + BASE_PORT));
intgetAvailablePort()
get Available Port
try (ServerSocket ss = new ServerSocket(0)) {
    ss.setReuseAddress(true);
    return ss.getLocalPort();
} catch (IOException e) {
} finally {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
...
intgetAvailablePort()
get Available Port
try (ServerSocket s = new ServerSocket(0)) {
    return s.getLocalPort();
} catch (Exception e) {
    throw new AssertionError("Failed to find available port", e);
intgetAvailablePort()
get Available Port
try {
    ServerSocket socket = new ServerSocket(0);
    try {
        return socket.getLocalPort();
    } finally {
        socket.close();
} catch (IOException e) {
...