Wednesday, February 20, 2013

[ Selenium 2.0 | WebDriver | Best practices ] How to check by URL that image exists


Check that URL leeds to existent image. For example, when you need to check that image was really uploaded.
Actually, you could use such solution to check any URL and it's response.


The Idea is to send an HTTP request by image-URL and check that response statuse code is OK (200)

Code sample

    // just look at your cookie's content (e.g. using browser) and import these settings from it
    private static final String SESSION_COOKIE_NAME = "JSESSIONID";
    private static final String DOMAIN = "";
    private static final String COOKIE_PATH = "/cookie/path/here";

    protected boolean isResourceAvailableByUrl(String resourceUrl) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        BasicCookieStore cookieStore = new BasicCookieStore();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        // resourceUrl - is url which leads to image
        HttpGet httpGet = new HttpGet(resourceUrl);

        try {
            HttpResponse httpResponse = httpClient.execute(httpGet, localContext);
            return httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
        } catch (IOException e) {
            return false;

    protected BasicClientCookie getSessionCookie() {
        Cookie originalCookie = webDriver.manage().getCookieNamed(SESSION_COOKIE_NAME);

        if (originalCookie == null) {
            return null;

        String cookieName = originalCookie.getName();
        String cookieValue = originalCookie.getValue();
        BasicClientCookie resultCookie = new BasicClientCookie(cookieName, cookieValue);
        return resultCookie;

No comments: