使用HtmlUnit下载文件 [英] Download file using HtmlUnit
问题描述
我正在尝试为网站下载xls文件。当我单击链接下载文件时,我得到一个JavaScript确认框。我像下面这样处理
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
ConfirmHandler okHandler = new ConfirmHandler(){
public boolean handleConfirm(Page page, String message) {
return true;
}
};
webClient.setConfirmHandler(okHandler);
有一个下载文件的链接。
There is a link to download file.
<a href="./my_file.php?mode=xls&w=d2hlcmUgc2VsbElkPSd3b3JsZGNvbScgYW5kIHN0YXR1cz0nV0FJVERFTEknIGFuZCBkYXRlIDw9IC0xMzQ4MTUzMjAwICBhbmQgZGF0ZSA%2BPSAtMTM1MDgzMTU5OSA%3D" target="actionFrame" onclick="return confirm('Do you want do download XLS file?')"><u>Download</u></a>
我点击链接使用
HTMLPage x = webClient.getPage("http://working.com/download");
HtmlAnchor anchor = (HtmlAnchor) x.getFirstByXPath("//a[@target='actionFrame']");
anchor.click();
handeConfirm()方法被执行。但是我不知道如何从服务器保存文件流。我试图用以下代码查看流。
handeConfirm() method is excuted. But I have no idea how to save the file stream from server. I tried to see the stream with code below.
anchor.click().getWebResponse().getContentAsString();
但是,结果与页面x相同。有人知道如何从服务器捕获流吗?谢谢。
But, the result is same as the page x. Anyone knows how to capture the stream from server? Thank you.
推荐答案
我找到了一种使用WebWindowListener获取InputStream的方法。在webWindowContentChanged(WebWindowEvent事件)内,我将代码放在下面。
I found a way to get InputStream using WebWindowListener. Inside of webWindowContentChanged(WebWindowEvent event), I put code below.
InputStream xls = event.getWebWindow().getEnclosedPage().getWebResponse().getContentAsStream();
得到xls后,可以将文件保存到硬盘中。
After I get xls, I could save the file into my hard disk.
这篇关于使用HtmlUnit下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!