java - 如果网站关闭(超时),如何获取服务器的状态?

标签 java selenium selenium-webdriver

网站宕机(超时)时如何获取服务器状态?

  1. 目前,如果网站已启动并正在运行,我的程序会识别服务器的状态。
  2. 例如,如果网站没问题 = 200。
  3. 如果显示错误页面 = 相关服务器状态。
  4. 如果网站关闭(超时),我的代码将无法工作,因此不会发送电子邮件。

代码: 获取服务器状态:

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

enter image description here

最佳答案

如 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/

相关文章:

selenium - 无法创建新的远程 session 。所需功能 = 功能 [{browserName=chrome, version=55.0.2, platform=WINDOWS}]

python - 如何使用 Python Selenium 拖放文件?

html - 使用 Selenium 查找具有流体 xpaths 的元素

java - Selenium 网格: How to retrieve node information from HUB programatically?

android - By和MobileBy的区别

java - jsonrpc4j : How to add type info to parameters?

java - SpringBoot应用程序中增强Log4J2版本

java - 使用 LibGDX 和 BaseGameUtils 创建 gameHelper 时如何修复空指针异常?

java - java中汉诺塔的打印函数

javascript - 在 WebDriverJS 中删除 cookie