如何獲取 Selenium WebDriver 的響應狀態程式碼?


我們可以用 Selenium webdriver 獲取響應狀態程式碼。執行測試時,我們可以驗證從伺服器獲得的響應程式碼。一些常見HTTP響應程式碼如下:-

  • 5XX 表示伺服器端出現問題。

  • 4XX 表示伺服器資源不可識別。

  • 3XX 表示請求已被重定向。

  • 2XX 表示請求已成功執行。

建立 HttpURLConnection 類的例項以獲得 HTTP 響應。要連結到一個 URL,請使用 openConnection 方法。然後,我們必須使用 setRequestMethod 方法並傳入 HEAD 作為引數。

要建立連線,應該將 connect 方法應用於 HttpURLConnection 類的物件。最後,getResponseCode 方法給出響應程式碼。

語法

HttpURLConnection cont=
(HttpURLConnection)new URL("https://tutorialspoint.tw/index.htm").
.openConnection();
cont.setRequestMethod("HEAD");
cont.connect();
int res = cont.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 HttpResponseStatus{
   public static void main(String[] args) throws
   MalformedURLException, IOException {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
      //url launch
      driver.get("https://tutorialspoint.tw/index.htm");
      //URL connection
      HttpURLConnection cont=
      (HttpURLConnection)new URL("https://tutorialspoint.tw/index.htm")
      .openConnection();
      // pass HEAD as parameter to setRequestMethod
      cont.setRequestMethod("HEAD");
      // obtain Response code
      cont.connect();
      int rs = cont.getResponseCode();
      System.out.println("Http response code: " + rs);
      //driver quit
      driver.quit();
   }
}

輸出

更新於:2021-6-29

3K+ 個瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.