使用 Selenium 檢查 HTTP 響應標頭的最佳方式


我們可以使用 Selenium webdriver 檢查 HTTP 響應標頭。要驗證 HTTP 標頭,我們應該從源頭上獲取響應。下面列出了一些 HTTP 響應程式碼 −

  • 5XX − 表示伺服器問題。

  • 4XX − 表示資源檢測問題。

  • 3XX − 表示響應重定向。

  • 2XX − 表示正確的程式碼。

HttpURLConnection 類用於獲取 HTTP 響應程式碼。要連結到某個 URL,需採用openConnection 方法。然後,我們必須使用setRequestMethod 方法,並向其傳遞HEAD 作為引數。

HttpURLConnection 類的物件上應用connect 方法。最後,使用getResponseCode 方法獲取響應程式碼。

語法

HttpURLConnection cn=
(HttpURLConnection)new URL("https://tutorialspoint.tw/index.htm").
.openConnection();
cn.setRequestMethod("HEAD");
cn.connect();
int rs = 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 HttpCodeResponse{
   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();
      driver.get("https://tutorialspoint.tw/questions/index.php");
      // wait of 8 seconds
      driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
      // establish connection with URL
      HttpURLConnection cn=
      (HttpURLConnection)new URL("https://tutorialspoint.tw/questions/index.php")
      .openConnection();
      // set the HEAD request
      c.setRequestMethod("HEAD");
      // connection initiated
      cn.connect();
      int res = cn.getResponseCode();
      System.out.println("Http response code: " + res);
      driver.close();
   }
}

輸出

更新於:2021 年 2 月 1 日

4 千次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告