简体   繁体   中英

Download a non html file with HtmlUnit

I'm writing a JUnit test that involves 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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