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 中启动的正确方法?
基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
