Search code examples
javanetwork-connection

How can I figure out network connection is available in java?


How can I figure out network connection is available in java? I want to get information about network connection. If it is available, I'll connect to network for fetching data otherwise I use local database.

Is There any solution?


Solution

  • Such as @igor said: "Try to connect the network, as you said. If fails, repeat e.g. 3 times. If still failling, use local database. You don't have to additionally ping anything."

    For Example:

        public class InternetConnection {
        /*  use at least one reliable host, in most cases you will want
            to use the one you're working with later    */
        private static final String CHECK_URL = "http://www.t-online.de/";
        public static InternetConnectionState isAvailable() {
            try {
                URL url = new URL(InternetConnection.CHECK_URL);
                HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
                Object objData = urlConnection.getContent();
            } catch(UnknownHostException exception) {
                return new InternetConnectionState(false);
            } catch(IOException exception) {
                return new InternetConnectionState(false);
            }
            return new InternetConnectionState(true);
        }
    }
    

    Main link