Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to test if server is up in Java?

What would be the proper way to simply see if a connection to a website/server can be made? I want this for an application I am coding that will just alert me if my website goes offline.

Thanks!

like image 854
DannyF247 Avatar asked Mar 12 '26 14:03

DannyF247


1 Answers

You can use an HttpURLConnection to send a request and check the response body for text that is unique to that page (rather than just checking to see if there's a response at all, just in case an error or maintenance page or something is being served).

Apache Commons has a library that removes a lot of the boiler plate of making Http requests in Java.

I've never done anything like this specifically on Android, but I'd be surprised if it's any different.

Here's a quick example:

URL url = new URL(URL_TO_APPLICATION);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream stream = connection.getInputStream();
Scanner scanner = new Scanner(stream); // You can read the stream however you want. Scanner was just an easy example
boolean found = false;
while(scanner.hasNext()) {
    String next = scanner.next();
    if(TOKEN.equals(next)) {
        found = true;
        break;
    }
}

if(found) {
    doSomethingAwesome();
} else {
    throw aFit();
}
like image 168
Joel Avatar answered Mar 14 '26 04:03

Joel