Capture Status Code, Fail Network Request, Add Custom Header – Selenium 4

Capture Status code, Fail Network Request​​ using Fetch method, Add custom header​​ -​​ Selenium 4

In this article, we would be looking at how to capture status code (example, 200) of​​ an api call (in Selenium 4),​​ how to deliberately fail a network request​​ plus how to add a custom header to an api request.

Let us first look at capturing status code. Go to the site​​ https://reqres.in/​​ 

Click the sample Request url seen above​​ https://reqres.in/api/users?page=2​​ 

Let us inspect this page and go to the Network section, notice the status code 200​​ 

Let us see how to capture this using CDT in Selenium 4.

The below piece of code will serve the purpose. We add a listener on line#25 that will listen to the responses that are received. The line#27 will print the respective api call that its status code. The api call is being made at line#31

Lets run it, notice the console o/p shown below

​​ 

This is how we can capture the status code for any api/website.

Let us now see how to fail a network request using Fetch method.

Let us launch site​​ http://zero.webappsecurity.com/​​ 

As you can see​​ above, right now we are able to launch this site.

The use case that we are trying to automate now is that, during runtime we would like to send some website url pattern and will ask Selenium to fail loading that website.

See below. We are sending a pattern in line#24.

In line#26, we are enabling the patterns using ‘Fetch’ method. In line#28, we are pausing the request during runtime (the request to launch​​ http://zero.webappsecurity.com/​​ that we have mentioned on line#36). So this will pause the request and look for the pattern ‘zero’. If the pattern matches, the Fetch.failRequest method will be fired (line 31)

​​ 

Run the script, notice below, the website did not load because the pattern matched​​ 

Let us give some incorrect pattern, see below

Run the script, notice below that website launches​​ 

So if your testing demands to fail a network request purposefully, you can use this approach.

Let us now see how to add a custom header to an api request.

If required, we can add a custom header(s) to an api request. Below code will serve the purpose (self-explanatory)​​ 

Run the script. Notice below that the custom header is added

Code snippet (status code)

package sel4scripts;

 

import java.util.Optional;

 

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.devtools.DevTools;

import org.openqa.selenium.devtools.v95.network.Network;

import org.openqa.selenium.devtools.v95.network.model.Headers;

 

import io.github.bonigarcia.wdm.WebDriverManager;

​​ 

public class CaptureStatusCode {

​​ 

public static void main(String[] args) {

​​ 

  WebDriverManager.chromedriver().setup();

  WebDriver driver = new ChromeDriver();

  driver.manage().window().maximize();

​​ 

  DevTools devTools = ((ChromeDriver) driver).getDevTools();

  devTools.createSession();

​​ 

  devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));

​​ 

  devTools.addListener(Network.responseReceived(), response -> {

​​ 

   System.out.println("Response URL is : "+response.getResponse().getUrl()+" ​​ status code is : "+response.getResponse().getStatus());

   

  });

  

  driver.get("https://reqres.in/api/users?page=2");

​​ 

​​ 

}

​​ 

}

 

Code snippet (Fail network request)

package sel4scripts;

 

import java.util.Arrays;

import java.util.List;

import java.util.Optional;

 

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.devtools.DevTools;

import org.openqa.selenium.devtools.v93.fetch.Fetch;

import org.openqa.selenium.devtools.v93.fetch.model.RequestPattern;

import org.openqa.selenium.devtools.v93.network.model.ErrorReason;

 

import io.github.bonigarcia.wdm.WebDriverManager;

 

public class FailNetworkRequest {

public static void main(String[] args) {

  WebDriverManager.chromedriver().setup();  

  WebDriver driver = new ChromeDriver();

 

  DevTools devTools = ((ChromeDriver) driver).getDevTools();

  devTools.createSession();

 ​​ ​​ ​​​​ 

Optional<List<RequestPattern>>patterns = Optional.of(Arrays.asList(new RequestPattern(Optional.of("*toscrape*"),Optional.empty(),Optional.empty())));

  

  devTools.send(Fetch.enable(patterns, Optional.empty()));

  

  devTools.addListener(Fetch.requestPaused(), request ->

  {

   

   devTools.send(Fetch.failRequest(request.getRequestId(), ErrorReason.FAILED));

   

  });

  

  

  driver.get("https://books.toscrape.com/");

}

}

 

Code snippet (custom header)

package​​ sel4scripts;

 

import​​ java.util.HashMap;

import​​ java.util.Map;

import​​ java.util.Optional;

import​​ org.openqa.selenium.WebDriver;

import​​ org.openqa.selenium.chrome.ChromeDriver;

import​​ org.openqa.selenium.devtools.DevTools;

import​​ org.openqa.selenium.devtools.v95.network.Network;

import​​ org.openqa.selenium.devtools.v95.network.model.Headers;

import​​ io.github.bonigarcia.wdm.WebDriverManager;

​​ 

public​​ class​​ AddCustomHeadersToAPIRequest {

​​ 

public​​ static​​ void​​ main(String[]​​ args) {

​​ 

 WebDriverManager.chromedriver().setup();

 WebDriver​​ driver​​ =​​ new​​ ChromeDriver();

driver.manage().window().maximize();

​​ 

 DevTools​​ devTools​​ = ((ChromeDriver)​​ driver).getDevTools();

devTools.createSession();

​​ 

devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));

​​ 

devTools.addListener(Network.requestWillBeSent(),​​ request​​ -> {

​​ 

 Headers​​ header​​ =​​ request.getRequest().getHeaders();

​​ 

if​​ (!header.isEmpty()) {

​​ 

 System.out.println("Request Headers: ");

header.forEach((key,​​ value) -> {

​​ 

 System.out.println(" ​​ "​​ +​​ key​​ +​​ " = "​​ +​​ value);

​​ 

 });

​​ 

 }

​​ 

 });

​​ 

devTools.addListener(Network.responseReceived(),​​ response​​ -> {

​​ 

 Headers​​ header​​ =​​ response.getResponse().getHeaders();

​​ 

if​​ (!header.isEmpty()) {

​​ 

 System.out.println("Response Headers: ");

header.forEach((key,​​ value) -> {

​​ 

 System.out.println(" ​​ "​​ +​​ key​​ +​​ " = "​​ +​​ value);

​​ 

 });

​​ 

 }

 System.out.println("Response URL is : "+response.getResponse().getUrl()+" ​​ status code is : "+response.getResponse().getStatus());

 });

 Map<String, Object>​​ headers​​ =​​ new​​ HashMap<String,Object>();

headers.put("customHeaderName",​​ "customHeaderValue");

headers.put("Testuser1",​​ "Full stack Tester");

 Headers​​ head​​ =​​ new​​ Headers(headers);

devTools.send(Network.setExtraHTTPHeaders(head));

driver.get("http://countrylayer.com/");

​​ 

 }

​​ 

}

 

Thank you for reading!

Share On

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on tumblr
Share on email

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Lifetime Membership Club

LIFETIME MEMBERSHIP BIG SALE - ALL LIVE COURES JUST - 7000 RS/ 99 USD
Attend All Live courses in just 7000 rs / $99 - offer ends 10th Nov 2024