I am trying to download xls file for a website. When I click the link to download the file, I get a javascript confirm box. I handle it like below
ConfirmHan
Expanding on Roy's answer, here's my solution to this problem:
public static void prepareForDownloadingFile(WebClient webClient, File output) {
webClient.addWebWindowListener(new WebWindowListener() {
public void webWindowOpened(WebWindowEvent event) {
}
public void webWindowContentChanged(WebWindowEvent event) {
Page page = event.getNewPage();
FileOutputStream fos = null;
InputStream is = null;
if (page != null && page instanceof UnexpectedPage) {
try {
fos = new FileOutputStream(output);
UnexpectedPage uPage = (UnexpectedPage) page;
is = uPage.getInputStream();
IOUtils.copy(is, fos);
webClient.removeWebWindowListener(this);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.close();
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void webWindowClosed(WebWindowEvent event) {
}
});
}
I felt there were enough differences to make it a new answer:
-Doesn't have a magic variable (response
)
-Closes InputStream
and FileOutputStream
-Looks for UnexpectedPage
to determine we're not on a HTML page
-Downloads a file one time after requesting then removes itself
-Doesn't require knowing the ContentType
Calling this once before, for example, clicking a button that initiates a download, will download that file.