How to get HTTP Response Code using Selenium WebDriver?

SeleniumAutomation TestingTesting Tools

We can get an HTTP response code in Selenium webdriver. While running test cases, we can check the response code from a resource. Common HTTP response codes include −

  • 5XX – Issue in server.

  • 4XX – Resource cannot be determined.

  • 3XX - Redirection.

  • 2XX – Fine.

An object of the class HttpURLConnection is created to get the HTTP response code. To establish a link to an URL, the openConnection method shall be used. Next, we shall utilize the setRequestMethod and pass HEAD as a parameter.

For connection, the connect method is to be applied to the instance of the HttpURLConnection class. At last, the getResponseCode method gets the response code.

Syntax

HttpURLConnection c=(HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm").
.openConnection();
c.setRequestMethod("HEAD");
c.connect();
int r = c.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 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://www.tutorialspoint.com/questions/index.php");
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // establish and open connection with URL
      HttpURLConnection c=
      (HttpURLConnection)new
      URL("https://www.tutorialspoint.com/questions/index.php")
      .openConnection();
      // set the HEAD request with setRequestMethod
      c.setRequestMethod("HEAD");
      // connection started and get response code
      c.connect();
      int r = c.getResponseCode();
      System.out.println("Http response code: " + r);
      driver.close();
   }
}

Output

raja
Published on 28-Dec-2020 15:45:53
Advertisements