在 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.tw/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.tw/index.htm"); // establish and open connection with URL HttpURLConnection cn= (HttpURLConnection)new URL("https://tutorialspoint.tw/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(); } }
輸出
廣告