How to get Response Status Code with Selenium WebDriver?

SeleniumAutomation TestingTesting Tools

We can get the Response status code with Selenium webdriver. While executing a test, we can verify the Response code obtained from a server. Some common HTTP Response codes are listed below −

  • 5XX means there is an issue on the server.

  • 4XX means that the server resource cannot be identified.

  • 3XX means the request has been redirected.

  • 2XX means the request executed successfully.

An instance of the class HttpURLConnection is created to obtain the HTTP Response. To have a link to an URL, the method openConnection method is used. Then we have to use the method setRequestMethod and pass HEAD as a parameter.

To have a connection, the method connect should be applied to an object of the class HttpURLConnection. Finally, the method getResponseCode gives the Response code.

Syntax

HttpURLConnection cont=
(HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm").
.openConnection();
cont.setRequestMethod("HEAD");
cont.connect();
int res = cont.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 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://www.tutorialspoint.com/index.htm");
      //URL connection
      HttpURLConnection cont=
      (HttpURLConnection)new URL("https://www.tutorialspoint.com/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();
   }
}

Output

raja
Published on 29-Jun-2021 07:51:56
Advertisements