Testing web server connection - Android

Asked

Viewed 345 times

2

I need to make a test connection with the web server, I am using this code below but all the attempts I made it always fall in the catch

HttpURLConnection conn = null;

        try {

                URL url = new URL("https://www.google.com");

                conn = (HttpURLConnection) url.openConnection();

                if (conn.getResponseCode() == conn.HTTP_OK) {
                    Toast.makeText(getApplicationContext(), "Conexao ok" ,Toast.LENGTH_LONG).show();
                    return  false;
                } else {
                    Toast.makeText(getApplicationContext(), "Conexao Problema", Toast.LENGTH_LONG).show();
                    return  false;
                }

        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Falha:" + e.getMessage()  ,Toast.LENGTH_LONG).show();
            return  false;
        } finally {
            if (conn != null) {
                Toast.makeText(getApplicationContext(), "Disconnect"  ,Toast.LENGTH_LONG).show();
                conn.disconnect();
            }
        } 
  • No catch which message it returns?

2 answers

3

Use the ConnectivityManager to check if there really is an Internet connection and, if any, what is the type of existing connection.

Determine if there is an Internet connection

There is no need to schedule an update based on an Internet resource if there is no Internet connection. The following snippet shows how to use Connectivitymanager to query the active network and determine if it has internet connectivity.

public static boolean isOnline(Context context) {
            ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}

Now, validate if there is a connection before executing any instruction.

if(isOnline(mContext)) {
   //restante do seu código
}
  • What does this do? It would be interesting to supplement your answer with some explanation... ;)

  • 1

    I will edit my reply in more detail. Thanks for the touch

0

Opa, blza!?

You can use the following function:

public boolean isOnline() throws InterruptedException, IOException
    {
        String command = "ping -c 1 google.com";
        return (Runtime.getRuntime().exec (command).waitFor() == 0);
    }

Replace google with your server URL.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.