开发者

Download a non html file with HtmlUnit

开发者 https://www.devze.com 2022-12-13 05:15 出处:网络
I\'m writing a JUnit test that inv开发者_如何学Colves the downloading of a file from the web app. How do I do that with HtmlUnit?I don\'t what kind of file, but maybe code for this test might be helpf

I'm writing a JUnit test that inv开发者_如何学Colves the downloading of a file from the web app. How do I do that with 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. downloadLink is the element with the link to the file you intend to download (a button, an input, an anchor...)

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消