
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get HTTP Response Code in Selenium with Java
We can get the HTTP response code in Selenium webdriver with Java. Some of the response codes are – 2xx, 3xx, 4xx and 5xx. The 2xx response code signifies the proper condition, 3xx represents redirection, 4xx shows resources cannot be identified and 5xx signifies server problems.
To obtain the response code we shall use the HttpURLConnection class. To have a link to the URL, the method openConnection is used. Also, we have to use the setRequestMethod where the vale Head is to be passed as a parameter.
We have to create an instance of the HttpURLConnection class and then apply the connect method on it. Finally, to obtain the response code the method getResponseCode is used.
Example
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 GetHttpResponse{ 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(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/index.htm"); // establish, open connection with URL HttpURLConnection cn = (HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm ").openConnection(); // set HEADER request cn.setRequestMethod("HEAD"); // connection initiate cn.connect(); //get response code int res = cn.getResponseCode(); System.out.println("Http response code: " + res); driver.quit(); } }
Output
Advertisements