Proper way to test if server is up in Java?

丶灬走出姿态 提交于 2019-12-06 03:18:06

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();
}

You want to also set the connection timeout using setConnectTimeout(int timeout) and setReadTimeout(int timeout). Otherwise the code might hang for a long time waiting for a non-responding server to reply.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!