Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quickly check if URL server is available

I have a URL in the form

http://www.mywebsite.com/util/conv?a=1&from=%s&to=%s

And want to check if it is available.

The links redirect me on a bad request page if I try to open these with a browser, however via code I can get the data that I need.

Using a try-catch block on a HTTP request procedure is pretty slow, so I'm wondering how I could ping a similar address to check if its server is active.


I have tried

boolean reachable = InetAddress.getByName(myLink).isReachable(6000);

But returns always false.

I have also tried

public static boolean exists(String URLName) {

    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
        con.setConnectTimeout(1000);
        con.setReadTimeout(1000);
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

That returns the correct value at the end of the process, bit is too slow if server is not available.

EDIT

I have understood what is the cause of slowness

a) if server returns some data but interrupts the request before complete the request the timeout is ignored and stuck until returns an Exception that lead the execution to reach the catch block, this is the cause of the slowness of this method, and still I haven't found a valid solution to avoid this.

b) If I start the android device and open the App without connection, the false value is returned correctly, if the app is opened with internet connection active and the device lost its internet connection happens the same thing of the case A (also if I try to terminate and restart the App... I don't know why, I suppose that something remains cached)

All this seems related to the fact Java URLConnection doesn't provide no fail-safe timeout on reads. Looking at the sample at this link I have seen that uses a thread to interrupt the connection in some way but if I add simply the line new Thread(new InterruptThread(Thread.currentThread(), con)).start(); like in the sample nothing changes.

like image 942
AndreaF Avatar asked Sep 12 '14 09:09

AndreaF


People also ask

How do you check if the URL is working?

Visit Website Planet. Enter the URL of your website address on the field and press the Check button. Website Planet will show whether your website is online or not.

How do you check whether the URL is working or not in Java?

Using a GET Request After that, we simply open the connection and get the response code: URL url = new URL("http://www.example.com"); HttpURLConnection huc = (HttpURLConnection) url. openConnection(); int responseCode = huc. getResponseCode(); Assert.


3 Answers

static public boolean isServerReachable(Context context) {
    ConnectivityManager connMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = connMan.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL urlServer = new URL("your server url");
            HttpURLConnection urlConn = (HttpURLConnection) urlServer.openConnection();
            urlConn.setConnectTimeout(3000); //<- 3Seconds Timeout 
            urlConn.connect();
            if (urlConn.getResponseCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (MalformedURLException e1) {
            return false;
        } catch (IOException e) {
            return false;
        }
    }
    return false;
}

or by using runtime:

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ping www.serverURL.com"); //<- Try ping -c 1 www.serverURL.com
int mPingResult = proc .waitFor();
if(mPingResult == 0){
    return true;
}else{
    return false;
}

You can try isReachable() but there is a bug filed for it and this comment says that isReachable() requires root permission:

try {
    InetAddress.getByName("your server url").isReachable(2000); //Replace with your name
    return true;
} catch (Exception e)
{
    return false;
}
like image 199
Sagar Pilkhwal Avatar answered Oct 20 '22 23:10

Sagar Pilkhwal


public static boolean exists(String URLName) {

        try {
            HttpURLConnection.setFollowRedirects(false);
            // note : you may also need
            // HttpURLConnection.setInstanceFollowRedirects(false)
            HttpURLConnection con = (HttpURLConnection) new URL(URLName)
            .openConnection();
            con.setRequestMethod("HEAD");
            return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
like image 28
BSavaliya Avatar answered Oct 21 '22 00:10

BSavaliya


have you tried using raw sockets?

It should run faster as it's on a lower layer

static boolean exists(String serverUrl)  {

    final Socket socket;

    try {
        URL url = new URL(serverUrl);
        socket = new Socket(url.getHost(), url.getPort());
    } catch (IOException e) {
        return false;
    }

    try {
        socket.close();
    } catch (IOException e) {
        // will never happen, it's thread-safe
    }

    return true;
}
like image 1
eridal Avatar answered Oct 20 '22 23:10

eridal