
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
Best Way to Inspect HTTP Response Headers with Selenium
We can inspect HTTP response headers with Selenium webdriver. To verify the HTTP header, we should get the response from a source. Some of the HTTP response codes are listed below −
5XX − Represents server concerns.
4XX − Represents issues in resource detection.
3XX − Represents response redirection.
2XX − Represents correct ocde.
The HttpURLConnection class is used to obtain the HTTP response code. To have a link to an URL, the method openConnection is used. Then, we have to use the setRequestMethod method and pass HEAD as parameter to it.
The connect method is applied on the object of the HttpURLConnection class. Finally, the method getResponseCode is used to obtain the response code.
Syntax
HttpURLConnection cn= (HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm"). .openConnection(); cn.setRequestMethod("HEAD"); cn.connect(); int rs = cn.getResponseCode();
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 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 8 seconds driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); // establish connection with URL HttpURLConnection cn= (HttpURLConnection)new URL("https://www.tutorialspoint.com/questions/index.php") .openConnection(); // set the HEAD request c.setRequestMethod("HEAD"); // connection initiated cn.connect(); int res = cn.getResponseCode(); System.out.println("Http response code: " + res); driver.close(); } }
Output
Advertisements