我们可以用 Java 中的 Selenium 获取 HTTP 响应代码吗?
我们可以用 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();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://tutorialspoint.com/index.htm");
// establish, open connection with URL
HttpURLConnection cn = (HttpURLConnection)new URL("https://tutorialspoint.com/index.htm ").openConnection();
// set HEADER request
cn.setRequestMethod("HEAD");
// connection initiate
cn.connect();
//get response code
int res = cn.getResponseCode();
System.out.println("Http response code: " + res);
driver.quit();
}
}输出

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