Download file using HtmlUnit

后端 未结 6 1947
一生所求
一生所求 2021-02-05 23:17

I am trying to download xls file for a website. When I click the link to download the file, I get a javascript confirm box. I handle it like below

    ConfirmHan         


        
6条回答
  •  猫巷女王i
    2021-02-05 23:59

    There's an easier way if you're not into wrapping HtmlUnit with Selenium. Simply provide HtmlUnit's WebClient with the extended WebWindowListener.

    You could also use Apache commons.io for easy stream copying.

    WebClient webClient = new WebClient();
    webClient.addWebWindowListener(new WebWindowListener() {
        public void webWindowOpened(WebWindowEvent event) { }
    
        public void webWindowContentChanged(WebWindowEvent event) {
            // Change or add conditions for content-types that you would
            // to like receive like a file.
            if (response.getContentType().equals("text/plain")) {
                try {
                    IOUtils.copy(response.getContentAsStream(), new FileOutputStream("downloaded_file"));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    
        public void webWindowClosed(WebWindowEvent event) {}
    });
    

提交回复
热议问题