I must add that although the final code block given above is good, it has one flaw - it is possible for it to take a very long time to contact the address specified, but the address is still reachable.
In my instance when testing with one address the method would return true, but take 10 seconds or longer to get a response. In this case the server was reachable, but not for any useful purposes since the connection was so slow. This occurs because the default timeout for HttpURLConnection
is 0, or infinite.
For this reason I'd recommend you do the checking off the UI thread, and add urlConnect.setConnectTimeout(1000);
before calling urlConnect.getContent();
This way you know the address is reachable, and that it won't take 5 years to download a 10k file.
(You might of course want to change the the timeout time to suit your needs)
Also I'd recommend not checking a generic address (google.com etc) unless your program generally accesses more than a few domains. If you're just accessing one or two then check that domain.