在 Selenium 中检查 HTTP 状态码。

seleniumautomation testingtesting tools更新于 2026/2/5 7:52:17

我们可以在 Selenium 中检查 HTTP 状态码。在运行测试时,我们可以验证资源响应的状态码。一些 HTTP 状态码为 −

  • 5XX - 服务器错误。

  • 4XX - 未检测到资源。

  • 3XX - 已重定向。

  • 2XX - 正常。

使用 HttpURLConnection 类的实例来获取 HTTP 状态码。要连接到 URL,请使用 openConnection 方法。然后,我们需要借助 setRequestMethod 并将 HEAD 作为参数传递给该方法。

要建立连接,需要将 connect 方法应用于 HttpURLConnection 类的对象。最后,使用 getResponseCode 方法获取 HTTP 响应代码。

语法

HttpURLConnection cn= (HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm")
.openConnection();
cn.setRequestMethod("HEAD");
cn.connect();
int c = cn.getResponseCode();

示例

代码实现。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class HttpRespCode{
   public static void main(String[] args) throws
   MalformedURLException, IOException {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // 等待 4 秒
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // 建立并打开与 URL 的连接
      HttpURLConnection cn= (HttpURLConnection)new
      URL("https://www.tutorialspoint.com/index.htm")
      .openConnection();
      // 使用 setRequestMethod 设置 HEAD 请求
      cn.setRequestMethod("HEAD");
      // 已发起连接并获取状态码
      cn.connect();
      int c = cn.getResponseCode();
      System.out.println("Http status code: " + c);
      driver.quit();
   }
}

输出


相关文章