How to Get Response Status Code with Selenium Webdriver Java
Selenium is an
open-source
web-based automation tool that is
implemented using a web driver. We will be using geckodriver
because Selenium 3 enables
geckodriver as the default WebDriver implementation for Firefox.
Pre-requisites:
- geckodriver.exe
- maven dependency selenium
<dependency> <groupid>org.seleniumhq.selenium</groupid> <artifactid>selenium-java</artifactid> <version>4.1.1</version> </dependency>
Steps:
it's a 4 steps process:
-
Set
webdriver.gecko.driver
and its'path
as a system property. - Set the firefox diver and browse to the website.
-
Get URL from web driver and try to open an HTTP connection using
java.net.HttpURLConnection
. - Get response code using the built-in function.
Let’s see all the above steps in the code. We will be using
HttpURLConnection.getResponseCode()
function to get the
response status:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; public class GetResponseCode { public static String GECKODRIVER_PATH = "F:\\WORK\\SeleniumShortTasks\\ResponseCode\\src\\main\\resources\\geckodriver.exe"; public static void main(String[] args) { //set firefox webdriver System.setProperty("webdriver.gecko.driver", GECKODRIVER_PATH); WebDriver driver = new FirefoxDriver(); //get the firefox browser & Browse the Website String siteLink = "https://www.oracle.com/java/"; driver.get(siteLink); try { // establish, open connection with URL HttpURLConnection cn = (HttpURLConnection) new URL(driver.getCurrentUrl()).openConnection(); // set HEADER request cn.setRequestMethod("HEAD"); // connection initiate cn.connect(); //get response code int res = cn.getResponseCode(); //Display System.out.println("Http response code: " + res); } catch (Exception e) { e.printStackTrace(); } //driver.quit(); } }
Output:
All resources used in this tutorial are attached:
- source code
- geckdriver.exe
Comments
Post a Comment