dimanche 4 décembre 2016

Get HtmlUnit webclient object by Java reflection?

I have a class to download csv file by htmlunit, but our team want to use java reflection to obtain WebClient obj of page itselt instead of instanciate new obj(WebClient wc = new WebClient();) so that we could retrieve more session data from it. And another reason of that is getting method of WebClient/htmlUnit is private.

Code:

public static void saveFile(Page page, String file) throws Exception {
      InputStream is = page.getWebResponse().getContentAsStream();
      FileOutputStream output = new FileOutputStream(file);
      IOUtils.copy(is, output);
      output.close();
 }    

public static void main(String...args) {  

      System.setProperty("webdriver.gecko.driver", "C:/Users/Haiqing/Downloads/geckodriver-v0.11.1-win64/geckodriver.exe");
      //DownloadFile df = new DownloadFile();
      WebDriver wd = new HtmlUnitDriver();
      WebClient wc = new WebClient(); 

      wd.get(ApplicationConstants.NYISO_URL);
      wd.switchTo().frame("MENU");
      WebElement zonalElement = wd.findElement(By.name("P-24Alist"));
      zonalElement.click();

      wd.switchTo().defaultContent();
      wd.switchTo().frame("BODY");   

      WebDriverWait wait = new WebDriverWait(wd, 10);
      WebElement mostRecentIntervalLink = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(text(),'Most recent interval')]")));
      String fileUrl = mostRecentIntervalLink.getAttribute("href");
      System.out.println("Target file url is: " + fileUrl);

    try{
        Page page = wc.getPage(fileUrl);
        File file =new File("c:/testDownload");    
           if  (!file .exists()  && !file .isDirectory()) {       
               System.out.println("folder not existed");  
               file .mkdir();
               System.out.println("folder successfully created andd start download file...");
           } else{  
               System.out.println("folder existed and start download file...");  
           }  

          saveFile(page, "c:/testDownload/targetFile.csv");
          System.out.println("Target file has successfully downloaded! Check 'testDownload' folder.");
    }
    catch(Exception e){

    }
    finally{
    wc.close();
    wd.quit();
    }

}





Aucun commentaire:

Enregistrer un commentaire