3

So, I'm trying to send POST requests to an IP adress, but I've found a problem way before that. To check if there's a working connection to the internet I have the following method called when creating the Activity:

public void checkInternectConnection() {
        AsyncTask.execute(() -> {

            try {
                InetAddress inAddress = InetAddress.getByName("https://google.com");
                if (inAddress.equals("")) {
                    networkAvilable = true;
                } else {
                    networkAvilable = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                networkAvilable = false;
            }
        });
}

When this code is executed, it always catches the exception java.net.UnkonwnHostException: Unable to resolve host "https://google.com": No address associated with hostname.

I've serched the error and all I can find is that the app doasn't have Internet permissions, but I have in the android manifest that permission already ( <uses-permission android:name="android.permission.INTERNET" />)

I've also tried with http://google.com instead of https, but nothing works.

Any ideas?

2
  • Have look this Commented Sep 10, 2018 at 11:47
  • InetAddress.getByName() takes a hostname, and the protocol (http://) is not part of the hostname. Check Muhammad's answer. Commented Sep 10, 2018 at 23:24

1 Answer 1

4

You need to check internet connection like this:

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null;
}

In manifest

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).

public boolean isInternetAvailable() {
    try {
        InetAddress ipAddr = InetAddress.getByName("google.com"); 
        //You can replace it with your name
            return !ipAddr.equals("");

        } catch (Exception e) {
            return false;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.