Java Ping pingHttp(URL url, int retry, int timeout)

Here you can find the source of pingHttp(URL url, int retry, int timeout)

Description

Pings an URL by using HttpURLConnection#getResponseCode() .

License

Open Source License

Parameter

Parameter Description
url the URL to ping
retry the number of tries
timeout the time (in milliseconds) between each tentative (can be zero)

Return

true if the ping succeeded, false otherwise

Declaration

public static boolean pingHttp(URL url, int retry, int timeout) 

Method Source Code

//package com.java2s;
/******************************************************************************
 * Copyright (c) 2009-2013, Linagora//w  w  w .j a  va  2  s . com
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *       Linagora - initial API and implementation
 *******************************************************************************/

import java.io.IOException;
import java.net.HttpURLConnection;

import java.net.URL;
import java.net.URLConnection;

public class Main {
    /**
     * Pings an URL by using {@link HttpURLConnection#getResponseCode()}.
     * <p>
     * Opens a connection for this URL.<br />
     * If the connection is an HTTP one, the response code must be 200.<br />
     * This connection is built at most <i>retry</i> times, every <i>timeout</i>
     * milliseconds, until the ping is successful.
     * </p>
     *
     * @param url the URL to ping
     * @param retry the number of tries
     * @param timeout the time (in milliseconds) between each tentative (can be zero)
     * @return true if the ping succeeded, false otherwise
     */
    public static boolean pingHttp(URL url, int retry, int timeout) {

        boolean success = false;
        for (int i = 0; i < retry && !success; i++) {
            try {
                URLConnection conn = url.openConnection();
                if (conn instanceof HttpURLConnection) {
                    int responseCode = ((HttpURLConnection) conn).getResponseCode();
                    success = 200 == responseCode;
                } else {
                    success = true;
                }

            } catch (IOException e) {
                success = false;
            }

            try {
                if (timeout > 0)
                    Thread.sleep(timeout);

            } catch (InterruptedException e) {
                // nothing
            }
        }

        return success;
    }
}

Related

  1. ping(String ip)
  2. pingHost(String host)
  3. ping(String url, int timeout)
  4. ping(String url, int timeout)
  5. pingUrl(final String address)
  6. pingURL(final String url)
  7. pingUrl(String Url)