Checking HTTP Status Code in Selenium.

SeleniumAutomation TestingTesting Tools

We can check HTTP status code in Selenium. As we run tests, we can verify the status code of a response from a resource. Some of the various HTTP status codes are −

  • 5XX – Error in server.

  • 4XX – Resource not detected.

  • 3XX - Redirected.

  • 2XX – Ok.

An instance of the class HttpURLConnection is used to get the HTTP status code. To have a connection to an URL, the openConnection method shall be utilized. Then we have to take the help of setRequestMethod and pass HEAD as a parameter to that.

To establish the connection, the connect method is to be applied to the object of the HttpURLConnection class. Finally, the getResponseCode method obtains the HTTP response code.

Syntax

HttpURLConnection cn= (HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm")
.openConnection();
cn.setRequestMethod("HEAD");
cn.connect();
int c = cn.getResponseCode();

Example

Code Implementation.

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://www.tutorialspoint.com/index.htm");
      // establish and open connection with URL
      HttpURLConnection cn= (HttpURLConnection)new
      URL("https://www.tutorialspoint.com/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();
   }
}

Output

raja
Published on 28-Dec-2020 16:24:19
Advertisements