Download file using HtmlUnit

后端 未结 6 1943
一生所求
一生所求 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条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 00:02

    Expanding on Roy's answer, here's my solution to this problem:

    public static void prepareForDownloadingFile(WebClient webClient, File output) {
        webClient.addWebWindowListener(new WebWindowListener() {
    
            public void webWindowOpened(WebWindowEvent event) {
            }
    
            public void webWindowContentChanged(WebWindowEvent event) {
                Page page = event.getNewPage();
                FileOutputStream fos = null;
                InputStream is = null;
                if (page != null && page instanceof UnexpectedPage) {
                    try {
                        fos = new FileOutputStream(output);
                        UnexpectedPage uPage = (UnexpectedPage) page;
                        is = uPage.getInputStream();
                        IOUtils.copy(is, fos);
                        webClient.removeWebWindowListener(this);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (fos != null)
                                fos.close();
                            if (is != null)
                                is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
    
            }
    
            public void webWindowClosed(WebWindowEvent event) {
            }
        });
    }
    

    I felt there were enough differences to make it a new answer:
    -Doesn't have a magic variable (response)
    -Closes InputStream and FileOutputStream
    -Looks for UnexpectedPage to determine we're not on a HTML page
    -Downloads a file one time after requesting then removes itself
    -Doesn't require knowing the ContentType

    Calling this once before, for example, clicking a button that initiates a download, will download that file.

提交回复
热议问题