使用 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.com/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.com/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.com/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 千次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.