Download a file without html using HtmlUnit

I am writing a JUnit test that involves downloading a file from a web application. How to do this using HtmlUnit?

+3
source share
2 answers

I do not know which file, but perhaps the code for this test may be useful. If not try to find the answers in other tests.

0
source

I bet you already solved the problem, but since this question is about the best google results when searching for "htmlunit download", here is a standard solution. downloadLink- this is an element with a link to the file that you are going to download (button, input, 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
source

Source: https://habr.com/ru/post/1724911/


All Articles