Thursday, April 19, 2018

How to get Response Status Code with Selenium WebDriver

Quite often when you are running automated checks with Selenium WebDriver, you also want to check the response status code for a resource, such as a web service or other webpages on the site. You can also check for broken links on the site as you are executing Selenium WebDriver scripts.

Let’s review the different http status codes:

2xx – OK
3xx – Redirection
4xx – Resource not found
5xx – Server error

In Selenium WebDriver there is no direct method to check the response status code, so we have to use another library for this. We can use Apache HttpClient or I prefer to use REST-assured library from Jayway

To get the response code using REST-assured we can use:

import com.jayway.restassured.response.Response;
import static com.jayway.restassured.RestAssured.given;

public class HttpResponseCode {

    public void checkHttpResponseCode(String url) {
        Response response =
                given().get(url)
                        .then().extract().response();

        System.out.println(response.getStatusCode());
    }

    public static void main(String args[]) {
        new HttpResponseCode().checkHttpResponseCode("http://www.google.com");
    }
}

No comments:

Post a Comment