Download file using HtmlUnit

后端 未结 6 1938
一生所求
一生所求 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-05 23:51

    I made it based on your post.. Note: you can change content-type condition for download only specific type of file. eg.( application/octect-stream, application/pdf, etc).

    package net.s4bdigital.export.main;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.List;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.htmlunit.HtmlUnitDriver;
    
    import com.gargoylesoftware.htmlunit.ConfirmHandler;
    import com.gargoylesoftware.htmlunit.Page;
    import com.gargoylesoftware.htmlunit.WebClient;
    import com.gargoylesoftware.htmlunit.WebResponse;
    import com.gargoylesoftware.htmlunit.WebWindowEvent;
    import com.gargoylesoftware.htmlunit.WebWindowListener;
    import com.gargoylesoftware.htmlunit.util.NameValuePair;
    
    public class HtmlUnitDownloadFile {
    
        protected String baseUrl;
        protected static WebDriver driver;
    
        @Before
        public void openBrowser() {
            baseUrl = "http://localhost/teste.html";
            driver = new CustomHtmlUnitDriver();
            ((HtmlUnitDriver) driver).setJavascriptEnabled(true);
    
        }
    
    
        @Test
        public void downloadAFile() throws Exception {
    
            driver.get(baseUrl);
            driver.findElement(By.linkText("click to Downloadfile")).click();
    
        }
    
        public class CustomHtmlUnitDriver extends HtmlUnitDriver { 
    
              // This is the magic. Keep a reference to the client instance 
               protected WebClient modifyWebClient(WebClient client) { 
    
    
                 ConfirmHandler okHandler = new ConfirmHandler(){
                        public boolean handleConfirm(Page page, String message) {
                            return true;
                        }
                 };
                 client.setConfirmHandler(okHandler);
    
                 client.addWebWindowListener(new WebWindowListener() {
    
                    public void webWindowOpened(WebWindowEvent event) {
                        // TODO Auto-generated method stub
    
                    }
    
                    public void webWindowContentChanged(WebWindowEvent event) {
    
                        WebResponse response = event.getWebWindow().getEnclosedPage().getWebResponse();
                        System.out.println(response.getLoadTime());
                        System.out.println(response.getStatusCode());
                        System.out.println(response.getContentType());
    
                        List headers = response.getResponseHeaders();
                        for(NameValuePair header: headers){
                            System.out.println(header.getName() + " : " + header.getValue());
                        }
    
                        // Change or add conditions for content-types that you would to like 
                        // receive like a file.
                        if(response.getContentType().equals("text/plain")){
                            getFileResponse(response, "target/testDownload.war");
                        }
    
    
    
                    }
    
                    public void webWindowClosed(WebWindowEvent event) {
    
    
    
                    }
                });          
    
                 return client; 
               } 
    
    
        } 
    
        public static void getFileResponse(WebResponse response, String fileName){
    
            InputStream inputStream = null;
    
            // write the inputStream to a FileOutputStream
            OutputStream outputStream = null; 
    
            try {       
    
                inputStream = response.getContentAsStream();
    
                // write the inputStream to a FileOutputStream
                outputStream = new FileOutputStream(new File(fileName));
    
                int read = 0;
                byte[] bytes = new byte[1024];
    
                while ((read = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
    
                System.out.println("Done!");
    
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        // outputStream.flush();
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
            }
    
        }
    
    }
    

提交回复
热议问题