Proper way to test if server is up in Java?(测试服务器是否在 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.
谢谢!
推荐答案
您可以使用 HttpURLConnection 发送请求并检查响应正文中是否有该页面唯一的文本(而不仅仅是检查是否有响应以防万一出现错误或维护页面或其他内容).
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 有一个库,可以删除很多制作模板Java 中的 Http 请求.
Apache Commons has a library that removes a lot of the boiler plate of making Http requests in Java.
我从来没有专门在 Android 上做过类似的事情,但如果有什么不同,我会感到惊讶.
I've never done anything like this specifically on Android, but I'd be surprised if it's any different.
这是一个简单的例子:
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();
}
这篇关于测试服务器是否在 Java 中启动的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:测试服务器是否在 Java 中启动的正确方法?


- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01