在 Selenium 中检查 HTTP 状态代码。
我们可以在 Selenium 中检查 HTTP 状态代码。当我们运行测试时,我们可以验证资源响应的状态代码。一些不同的 HTTP 状态代码如下 −
5XX – 服务器错误。
4XX – 未检测到资源。
3XX - 已重定向。
2XX – 正常。
类 HttpURLConnection 的实例用于获取 HTTP 状态代码。要连接某个 URL,可以使用 openConnection 方法。然后,我们可以借助 setRequestMethod 并将 HEAD 作为参数传递给它。
要建立连接,必须将 connect 方法应用于 HttpURLConnection 类的对象。最后,getResponseCode 方法获取 HTTP 响应代码。
语法
HttpURLConnection cn= (HttpURLConnection)new URL("https://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();
// wait of 4 seconds
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
driver.get("https://tutorialspoint.com/index.htm");
// establish and open connection with URL
HttpURLConnection cn= (HttpURLConnection)new
URL("https://tutorialspoint.com/index.htm")
.openConnection();
// set the HEAD request with setRequestMethod
cn.setRequestMethod("HEAD");
// connection initiated and obtain status code
cn.connect();
int c = cn.getResponseCode();
System.out.println("Http status code: " + c);
driver.quit();
}
}输出

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