【问题标题】:Missing attachment on xhr download with HtmlUnit使用 HtmlUnit 下载 xhr 时缺少附件
【发布时间】:2019-08-20 01:45:57
【问题描述】:

我正在尝试从基于 liferay+struts+angular 的网站自动下载一些文件(使用 HtmlUnit)。 到目前为止,HtmlUnit 在导航页面和解释 JS 方面做得很好,但是当我尝试下载文件时,它返回给我的是相同的页面而不是附件。

下载按钮是这样制作的:

<button class="btn" name="filedownload" data-ng-disabled="false"
        type="button" data-ng-lick="vm.downloadFile(...things...)">
</button>

我已经尝试了我在网上找到的两种主要技术:使用CollectingAttachmentHandler.getWebResponse().getContentAsStream(),它们都给了我起始页而不是附件。

通过使用 Chrome 的网络跟踪器跟踪它,我看到一旦我点击它就会调用 2 个不同的端点,第一个跟踪此类文件将被加载,第二个跟踪下载文件,第二个有一个使用正确的 Content-Disposition: attachment; filename= 标头响应,但显然 HtmlUnit 没有拾取它。

这是我尝试过的一些sn-p代码。

CollectingAttachmentHandler attachmentHandler = new 
CollectingAttachmentHandler();
client.setAttachmentHandler(attachmentHandler);
attachmentHandler.handleAttachment(myButton.click());

// I get only one attachment, the page
List<Attachment> attachments = attachmentHandler.getCollectedAttachments();
try (InputStream in = myButton.click().getWebResponse().getContentAsStream();
     OutputStream out = Files.newOutputStream(new File(""...my_file...).toPath())) {
    IOUtils.copy(in, out);
}
// In my file I find the page

编辑: 我在 HtmlUnit 的 github 上开了一张票,作者很慷慨地回复并给了我一些建议,比如检查新窗口是否打开client.getWebWindows()。不幸的是,这不是我的情况,但我也会在这里发布,以防有​​人觉得它有帮助。

【问题讨论】:

    标签: java download xmlhttprequest htmlunit


    【解决方案1】:

    至少您可以使用 WebConnectionWrapper 拦截/获取所有请求-响应周期的通知。 有关简短示例,请参阅 http://htmlunit.sourceforge.net/faq.html#HowToModifyRequestOrResponse

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      相关资源
      最近更新 更多