If your Selenium tests run in a modern browser, an easy way to obtain the response code is to send a synchronous XMLHttpRequest
* and check the status
of the response:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://exampleurl.ex', false);
xhr.send(null);
assert(200, xhr.status);
You can use this technique with any programming language by requesting that Selenium execute the script. For example, in Java you can use JavascriptExecutor.executeScript()
to send the XMLHttpRequest
:
final String GET_RESPONSE_CODE_SCRIPT =
"var xhr = new XMLHttpRequest();" +
"xhr.open('GET', arguments[0], false);" +
"xhr.send(null);" +
"return xhr.status";
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver;
Assert.assertEquals(200,
javascriptExecutor.executeScript(GET_RESPONSE_CODE_SCRIPT, "http://exampleurl.ex"));
* You could send an asynchronous XMLHttpRequest
instead, but you would need to wait for it to complete before continuing your test.
You can obtain the response code in Java by using URL.openConnection()
and HttpURLConnection.getResponseCode()
:
URL url = new URL("http://exampleurl.ex");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
// You may need to copy over the cookies that Selenium has in order
// to imitate the Selenium user (for example if you are testing a
// website that requires a sign-in).
Set<Cookie> cookies = webDriver.manage().getCookies();
String cookieString = "";
for (Cookie cookie : cookies) {
cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
}
httpURLConnection.addRequestProperty("Cookie", cookieString);
Assert.assertEquals(200, httpURLConnection.getResponseCode());
This method could probably be generalized to other languages as well but would need to be modified to fit the language's (or library's) API.