我们可以使用 Java 在 Selenium 中获取 HTTP 响应代码吗?

seleniumautomation testingtesting tools更新于 2026/1/23 23:52:17

我们可以使用 Java 在 Selenium WebDriver 中获取 HTTP 响应代码。一些响应代码包括 2xx、3xx、4xx 和 5xx。2xx 响应代码表示状态正常,3xx 表示重定向,4xx 表示无法识别资源,5xx 表示服务器问题。

要获取响应代码,我们将使用 HttpURLConnection 类。要获取指向 URL 的链接,请使用 openConnection 方法。此外,我们必须使用 setRequestMethod 方法,其中将 Head 值作为参数传递。

我们必须创建 HttpURLConnection 类的实例,然后在其上应用 connect 方法。最后,要获取响应代码,请使用 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 GetHttpResponse{
   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();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://www.tutorialspoint.com/index.htm");
      // 建立并打开与 URL 的连接
      HttpURLConnection cn = (HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm ").openConnection();
      // 设置 HEADER 请求
      cn.setRequestMethod("HEAD");
      // 发起连接
      cn.connect();
      // 获取响应码
      int res = cn.getResponseCode();
      System.out.println("Http response code: " + res);
      driver.quit();
   }
}

输出


相关文章