简体   繁体   English

使用HtmlUnit下载非html文件

[英]Download a non html file with HtmlUnit

I'm writing a JUnit test that involves the downloading of a file from the web app. 我正在编写一个JUnit测试,涉及从Web应用程序下载文件。 How do I do that with HtmlUnit? 我如何使用HtmlUnit做到这一点?

I don't what kind of file, but maybe code for this test might be helpful. 我不是什么样的文件,但是这个测试的代码可能会有所帮助。 If not try to find answers in other tests. 如果没有尝试在其他测试中找到答案。

I'd bet you already solved the problem, but since this question is on google's top results when searching for "htmlunit download", here's the standard solution. 我敢打赌你已经解决了这个问题,但是因为这个问题是google搜索“htmlunit download”时的最佳结果,这里是标准解决方案。 downloadLink is the element with the link to the file you intend to download (a button, an input, an anchor...) downloadLink是带有您要下载的文件的链接的元素(按钮,输入,锚点......)

try {
    InputStream is = downloadLink.click().getWebResponse().getContentAsStream();
    try {
        File f = new File("filename.extension");
        OutputStream os = new FileOutputStream(f);
        byte[] bytes = new byte[1024]; // make it bigger if you want. Some recommend 8x, others 100x
        while (read = is.read(bytes)) {
            os.write(bytes, 0, read);
        }
        os.close();
        is.close();
    } catch (IOException ex) {
        // Exception handling
    }
} catch (IOException ex) {
    // Exception handling
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM