Recently I was asked to write a Neustar script to download files from the browser. The goal of the script would be to calculate the sites performance during [X] downloads.
The following is the download step:
test.beginStep("Download"); var wrapper = driver.findElement(By.className("download-wrapper")); // Find the name, size, and url of the download var downloadName = wrapper.findElement(By.cssSelector(".download-info")).getText(); var downloadSize = wrapper.findElement(By.cssSelector(".size")).getText(); var downloadUrl = wrapper.findElement(By.partialLinkText("DOWNLOAD")).getAttribute("href"); // Fix name and size // Name: [EpicDownload.zip\n] (remove ' \n') // Size: [99999999 bytes] (remove ' bytes') downloadName = downloadName.substr(0, downloadName.indexOf("\n")); downloadSize = downloadSize.substr(0, downloadSize.indexOf(" ")); // Create the httpClient with the cookies from Selenium var client = driver.getHttpClient(); client.setFollowRedirects(true); client.setCheckValidSSL(false); // Test sites usually have invalid certs client.setSocketOperationTimeout(60000); // This value will change depending on the site requirements // If your site requires cookie authentication (Jsessionid) then we need to add the cookies // to the httpRequest from Selenium. var javaCookies = driver.manage().getCookies(); // Create the http GET request on the download url var httpGet = client.newGet(downloadUrl); // Call to custom setCookies function to add all the cookies to the http request var httpRequest = setCookies(javaCookies, httpGet); //Download the file to memory (do not write to the file system) test.log("Starting download: " + downloadName + " [" + downloadSize + " bytes]"); // This will download the file from the server into memory var httpResponse = httpRequest.execute(); // For our test we didn't need to assert anything but you could check that the download size is // correct. Or the file name matches your expected. var transactionStepObject = httpResponse.getInfo(); test.log("Download completed [" + transactionStepObject.getBytes() + " bytes] in " + transactionStepObject.getTimeActive() + "ms"); test.endStep(); //--- Util Functions // Takes an array of javaCookies (from Selenium) and adds them to the httpRequest var setCookies = function setCookies(javaCookies, httpRequest) { var javaCookiesArray = javaCookies.toArray(); var cookieString = ""; // Populate the cookieString with all cookies currently contained in the driver for (var i = 0; i < javaCookiesArray.length; i++) { var cookie = javaCookiesArray[i]; cookieString += cookie.getName() + "=" + cookie.getValue() + ", domain=" + cookie.getDomain() + ", path=" + cookie.getPath() + "; "; } // Add the cookies as a request header httpRequest.addRequestHeader("Cookie", cookieString); return httpRequest; };