简体   繁体   English

正确的方法来测试服务器是否在Java中运行?

[英]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! 谢谢!

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). 您可以使用HttpURLConnection发送请求并检查响应正文以查找该页面唯一的文本(而不仅仅是检查是否存在响应,以防出现错误或维护页面或某些内容) 。

Apache Commons has a library that removes a lot of the boiler plate of making Http requests in Java. Apache Commons有一个库,可以删除许多用Java编写Http请求的样板。

I've never done anything like this specifically on Android, but I'd be surprised if it's any different. 我从来没有在Android上做过这样的事情,但如果有任何不同,我会感到惊讶。

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) . 您还想使用setConnectTimeout(int timeout)setReadTimeout(int timeout)设置连接超时。 Otherwise the code might hang for a long time waiting for a non-responding server to reply. 否则代码可能会挂起很长时间,等待无响应的服务器回复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM