After looking at our available options, we are going to go with the least complex solution and extend our existing code. In our scenario, HttpOnly cookies are not a problem because we don't use them, so we don't have to worry about any potential issues relating to them.
We don't need to change any of our existing code; instead we are going to write a new method that will take the connection we have already negotiated with the server and use it to complete the file download:
public File downloadFile() throws Exception {
File downloadedFile = File.createTempFile("download", ".pdf");
HttpResponse fileToDownload = makeHTTPConnection();
try {
FileUtils.copyInputStreamToFile(fileToDownload.getEntity()
.getContent(), downloadedFile);
} finally {
fileToDownload.getEntity().getContent().close();
}
return downloadedFile;
}
This method will create a file in our temporary directory and then, using the connection we have already negotiated with the remote server, stream all the data from the remote file into it. We then close the connection to the remote server and return the file.
We are using a standard Java library to create a temporary file because this will guarantee that our file is unique. The other benefit is that, since we are putting this file in the temp directory, it will automatically get cleaned up by the operating system when required; we don't have to do the cleanup ourselves.
Let's plug this new code into a test to see how it works:
@Test
public void downloadAFile() throws Exception {
FileDownloader downloadHandler = new FileDownloader(driver);
driver.get("http://web.masteringselenium.com/
downloadTest.html");
WebElement fileThatShouldExist =
driver.findElement(By.id("fileToDownload"));
URI fileAsURI = new
URI(fileThatShouldExist.getAttribute("href"));
downloadHandler.setURI(fileAsURI);
downloadHandler.setHTTPRequestMethod(RequestType.GET);
File downloadedFile = downloadHandler.downloadFile();
assertThat(downloadedFile.exists()).isEqualTo(true);
assertThat(downloadHandler.getLinkHTTPStatus()).isEqualTo(200);
}