如何使用 Selenium WebDriver 获取 HTTP 响应代码?
seleniumautomation testingtesting tools
我们可以在 Selenium WebDriver 中获取 HTTP 响应代码。在运行测试用例时,我们可以检查资源的响应代码。常见的 HTTP 响应代码包括 −
5XX - 服务器问题。
4XX - 无法确定资源。
3XX - 重定向。
2XX - 正常。
创建 HttpURLConnection 类的对象来获取 HTTP 响应代码。要建立到 URL 的链接,需要使用 openConnection 方法。接下来,我们将使用 setRequestMethod 并传递 HEAD 作为参数。
为了进行连接,我们将对 HttpURLConnection 类的实例应用 connect 方法。最后,使用 getResponseCode 方法获取响应代码。
语法
HttpURLConnection c=(HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm").
.openConnection();
c.setRequestMethod("HEAD");
c.connect();
int r = c.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 HttpCodeResponse{
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.get("https://www.tutorialspoint.com/questions/index.php");
// 等待 5 秒
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// 使用 URL 建立并打开连接
HttpURLConnection c=
(HttpURLConnection)new
URL("https://www.tutorialspoint.com/questions/index.php")
.openConnection();
// 使用 setRequestMethod 设置 HEAD 请求
c.setRequestMethod("HEAD");
// 连接已启动并获取响应代码
c.connect();
int r = c.getResponseCode();
System.out.println("Http response code: " + r);
driver.close();
}
}
输出


