网站宕机(超时)时如何获取服务器状态?
- 目前,如果网站已启动并正在运行,我的程序会识别服务器的状态。
- 例如,如果网站没问题 = 200。
- 如果显示错误页面 = 相关服务器状态。
- 如果网站关闭(超时),我的代码将无法工作,因此不会发送电子邮件。
代码: 获取服务器状态:
public class ServerStatus {
public static int getResponseCode(String urlString) throws MalformedURLException, IOException {
URL url = new URL(urlString);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("GET");
huc.connect();
return huc.getResponseCode();
}
}
通过电子邮件发送所获取信息的状态(如果服务器关闭/超时“我的问题”,则不起作用):
public void EmailFormatAndDataCapture(ITestResult testResult) throws MalformedURLException, IOException {
if (testResult.getStatus() == ITestResult.FAILURE || testResult.getStatus() == ITestResult.SKIP) {
String tempTime = new SimpleDateFormat("hh.mm.ss").format(new Date());
serverStatusMap.put("\n Time:" + tempTime + " , Test Method: " + testResult.getName() + ", Server Status", ServerStatus.getResponseCode(basePage.getCurrentURL().toString()));
failedSkippedTests.put("\n Time:" + tempTime, " Class name: " + this.getClass().getSimpleName().toString() + ", Test Method Name: " + testResult.getName());
}
}
最佳答案
如 getResponseCode() 文档中所述,它会抛出 IOException - 如果连接到服务器时发生错误。
https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#getResponseCode()
您应该使用 try catch 子句处理此异常。例如:
try{
// here getStatus
} catch (IOException e){
// handle your timeout scenario
}
编辑:
当您尝试建立连接时,可能会提前抛出异常,因此您必须选择需要捕获异常的位置以满足您的要求。
关于java - 如果网站关闭(超时),如何获取服务器的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42087643/