Android: check server connection

So, I have a method that checks if a device is connected to the Internet based on this

It works fine, but on several occasions I found that although the phone shows that it is connected to the Internet, it still does not have access to my server. What I'm really looking for is to test this connection to my specific URL.

How could I implement this?

+5
source share
3 answers

You can do something like:

public boolean isConnectedToServer(String url, int timeout) {
    try{
        URL myUrl = new URL(url);
        URLConnection connection = myUrl.openConnection();
        connection.setConnectTimeout(timeout);
        connection.connect();
        return true;
    } catch (Exception e) {
        // Handle your exceptions
        return false;
    }
}

This will try to connect to your server url, and if it fails, you obviously have no connection .; -)

+24
source

You can try

InetAddress.getByName(host).isReachable(timeOut)
+2
source
Runtime runtime = Runtime.getRuntime();
            Process proc;
            try {
                proc = runtime.exec("ping -c 1"+ (String) getText(R.string.Server));
                proc.waitFor();
                int exit = proc.exitValue();
                if (exit == 0) { // normal exit


                } else { // abnormal exit, so decide that the server is not
                            // reachable


                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } // other servers, for example
            catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
0

All Articles