Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.4k points)

How to get the HTTP status code in Selenium?

E.g. so I can test that if the browser requests /user/27 and no user with ID=27 exists, an HTTP 404 is returned?

My primary interest is Selenium RC, but if someone knows the answer for "normal" selenium, I can probably easily translate it into RC.

1 Answer

0 votes
by (27.5k points)

Yes, you can get the http request's response code using Selenium with either Chrome or Firefox. But the trick is that you have to start them in logging mode. You have to tell chromedriver to do "Network.enable". This can be achieved by enabling performance logging. Let me give you an example.

LoggingPreferences logPrefs = new LoggingPreferences();

logPrefs.enable(LogType.PERFORMANCE, Level.ALL);

cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

Once the request is posted, you have to simply iterate the Perfomance logs and look for "Network.responseReceived" for requested url:

LogEntries logs = driver.manage().logs().get("performance");

Below is my complete code:

public class TestResponseCode

{

    public static void main(String[] args)

    {

        String url = "http://www.york.ac.uk/teaching/cws/wws/webpage1.html";

        DownloadPage(url);

    }

    private static void DownloadPage(String url)

    {

        ChromeDriver driver = null;

        try

        {

            ChromeOptions options = new ChromeOptions();

            // add the extensions you need

            // for instance I needed one of adding proxy, and one for blocking

            // images

            // options.addExtensions(new File(file, "proxy.zip"));

            // options.addExtensions(new File("extensions",

            // "Block-image_v1.1.crx"));

            DesiredCapabilities cap = DesiredCapabilities.chrome();

            cap.setCapability(ChromeOptions.CAPABILITY, options);

            // set performance logger

            // this sends Network.enable to chromedriver

            LoggingPreferences logPrefs = new LoggingPreferences();

            logPrefs.enable(LogType.PERFORMANCE, Level.ALL);

            cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

            driver = new ChromeDriver(cap);

            // navigate to the page

            System.out.println("Navigate to " + url);

            driver.navigate().to(url);

            // Now capture the last recorded url (it may be a redirect, or the

            // original url)

            String currentURL = driver.getCurrentUrl();

            // then ask for all the performance logs from this request

            // one of them will contain the Network.responseReceived method

            // we will find the "last recorded url" response

            LogEntries logs = driver.manage().logs().get("performance");

            int status = -1;

            System.out.println("\nList of log entries:\n");

            for (Iterator<LogEntry> it = logs.iterator(); it.hasNext();)

            {

                LogEntry entry = it.next();

                try

                {

                    JSONObject json = new JSONObject(entry.getMessage());

                    System.out.println(json.toString());

                    JSONObject message = json.getJSONObject("message");

                    String method = message.getString("method");

                    if (method != null

                            && "Network.responseReceived".equals(method))

                    {

                        JSONObject params = message.getJSONObject("params");

                        JSONObject response = params.getJSONObject("response");

                        String messageUrl = response.getString("url");

                        if (currentURL.equals(messageUrl))

                        {

                            status = response.getInt("status");

                            System.out.println(

                                    "---------- bingo !!!!!!!!!!!!!! returned response for "

                                            + messageUrl + ": " + status);

                            System.out.println(

                                    "---------- bingo !!!!!!!!!!!!!! headers: "

                                            + response.get("headers"));

                        }

                    }

                } catch (JSONException e)

                {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

            System.out.println("\nstatus code: " + status);

        } finally

        {

            if (driver != null)

            {

                driver.quit();

            }

        }

    }

}

Browse Categories

...