如何使用 Selenium WebDriver 获取 HTTP 响应代码?
我们可以在 Selenium 驱动程序中获取一个 HTTP 响应代码。在运行测试用例的同时,我们可以检查资源中的响应代码。常见的 HTTP 响应代码包括 -
5XX – 服务器问题。
4XX – 无法确定资源。
3XX - 重定向。
2XX – 正常。
为了获取 HTTP 响应代码,将创建一个 HttpURLConnection 类的对象。要建立到 URL 的链接,应使用 openConnection 方法。接下来,我们将使用 setRequestMethod 并将 HEAD 作为参数传递。
对于连接,需要将 connect 方法应用到 HttpURLConnection 类的实例。最后,getResponseCode 方法将获取响应代码。
语法
HttpURLConnection c=(HttpURLConnection)new URL("https://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://tutorialspoint.com/questions/index.php");
// wait of 5 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// establish and open connection with URL
HttpURLConnection c=
(HttpURLConnection)new
URL("https://tutorialspoint.com/questions/index.php")
.openConnection();
// set the HEAD request with setRequestMethod
c.setRequestMethod("HEAD");
// connection started and get response code
c.connect();
int r = c.getResponseCode();
System.out.println("Http response code: " + r);
driver.close();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP