BLOG

Img
Ankush Bansal Author's Perspective
img
5 Minutes read

How to check the response code using Selenium WebDriver

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped into five classes:

  • Informational responses
  • Successful responses
  • Redirects
  • Client errors
  • Server errors

To identify various hyperlinks in a webpage, manual validation can be done though manual efforts will increase. It can take hours as manually each link needs to be opened in the browser which takes its own time.

However, if we use Selenium along with HTTPURLConnection class, the same can be done in a matter of a few minutes. This saves a lot of time as after opening the browser http connection checks response code without opening the same in browser and only by hitting the specified URL using http connection only.

Prerequisite:

  • Method (POST/PUT/GET/DELETE/etc.)
  • URL (/oauth/token which will follow the URL for the instance of qTest you’re using)
  • Headers
  • Body

Benefits of using API testing with Selenium

  • Leverage Open source tools
  • Integrate in minutes
  • Time-saving
  • Cost-effectiveness

Below are the steps we need to follow for sending Java HTTP requests using HttpURLConnection class:

  • Create a URL object from the GET/POST URL String.
  • Call openConnection() method on URL object that returns instance of HttpURLConnection
  • Set the request method in HTTPURLConnection instance, the default value is GET.
  • Call setRequestProperty() method on HTTPURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language” etc.
  • We can call getResponseCode() to get the response HTTP code. This way we know if the request was processed successfully or there was an HTTP error message thrown.
  • For GET, we can simply use Reader and InputStream to read the response and process it accordingly.
  • For POST, before we read response we need to get the OutputStream from HTTPURLConnection instance and write POST parameters into it.

Use the below code to test the API Get Method using selenium:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpResponseGetMethod {
public static void main(String[] args) throws IOException {
String URL = "URL to test";
int code;

String Userid[] = new String[2];
HttpURLConnection.setFollowRedirects(false);
// Creating object of HTTPUrl connection for each url and opening
connection
HttpURLConnection con = (HttpURLConnection) new
URL(URL).openConnection();
// Setting request method as Head/get
con.setRequestMethod("GET");
con.setRequestProperty("Accept-Charset", "UTF-8");
// Getting page Response code
code = con.getResponseCode();
System.out.println(code);
System.out.println(con.getInputStream());
BufferedReader in = new BufferedReader(new
InputStreamReader(con.getInputStream()));
StringBuffer response = new StringBuffer();
for (int i = 0; i <= 10;="" i++)="">
while ((line = in.readLine()) != null) {
response.append(line + "\n");
String x = response.toString();
System.out.println(response.toString());
Userid = x.split(",");
System.out.println(Userid[0] + " ------ " + Userid[1]);
}}
in.close();}}

Use the below code to test the API Post Method using selenium:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpResponsePostMethod {
public static void main(String[] args) throws MalformedURLException,
IOException {
String URL = "Url to test";
int code;
HttpURLConnection con = (HttpURLConnection) new
URL(URL).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept-Charset", "UTF-8");
String body = "Body to pass";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(body);
wr.flush();
wr.close();
code = con.getResponseCode();
System.out.println(code);
System.out.println(body);
System.out.println(con.getInputStream());
BufferedReader in = new BufferedReader(new
InputStreamReader(con.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(line + "\n");
}
in.close();
System.out.println(response.toString());
}}

Ebook
Top 10 Sitecore 9 Form Features to Increase Lead Conversions
Ankush Bansal Sr. Practice Manager - Testing


Talk to our Experts

Talk to us about how we bring together 1:1 personalisation, deep Martech Expertise, CX & Demand Gen Strategy, Engagement Analytics & Cross-Channel Orchestration to drive award winning experiences that convert

Get in touch for a complimentary consultation or a demo today.

Expert Workshops

Free workshops, expert advice & demos- to help your realize value with Sitecore

Register

Session Presentations

  • Sitecore + SFMC= Marketing Success
  • Transforming The Future Of eCommerce
Meet Us

Giveaways:

Participate in our event survey , meet us at our booth , get free giveaways & a chance to win an iPhone 11

Let’s go
Close Button