我們可以用 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.tw/index.htm");
// establish, open connection with URL
HttpURLConnection cn = (HttpURLConnection)new URL("https://tutorialspoint.tw/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