-4

When I want to reach a server, url or website, my function returns false everytime. I want a function that indicates me the code status 200, the function must wait I think to give me a true or a false... I don't want async solutions.

 private boolean isServerReachable() {
        try {
            InetAddress.getByName("http://www.google.com").isReachable(2000); 
            return true;
        } catch (Exception e)
        {
            return false;
        }
    }

Any ideas ? I based my code on that ticket that is popular: Ticket 1 Thanks in advance

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
ΩlostA
  • 2,501
  • 5
  • 27
  • 63
  • @jeprubio this ticket is very popular and talks about it: https://stackoverflow.com/questions/285860/how-can-i-programmatically-test-an-http-connection – ΩlostA Mar 20 '20 at 10:49
  • _"Any ideas ?"_ Yes, search for "android.os.NetworkOnMainThreadException" and you'll understand the problem. There's a way to disable the [StrictMode](https://developer.android.com/reference/android/os/StrictMode) that prevents network on main thread however. On the other hand you can make it "kind of synchoronous" with Java's [Future](https://www.baeldung.com/java-future) for example if you wait for `isDone()` to return true and use a Thread inside the Future. But is it a good solution, really? – Markus Kauppinen Mar 20 '20 at 10:55
  • @MarkusKauppinen thank you. But why this ticket is so popular if this doesn't work ? https://stackoverflow.com/questions/285860/how-can-i-programmatically-test-an-http-connection – ΩlostA Mar 20 '20 at 11:04
  • @jeprubio this ticket very very very popular does it, for android, https://stackoverflow.com/a/9570292/3581620 – ΩlostA Mar 20 '20 at 11:16
  • @jeprubio In my question, I put the google.com site. I have an error for this. No logical – ΩlostA Mar 20 '20 at 11:18

1 Answers1

-1

You can change "http://www.google.com" to google.com this parameter is host name.