Search code examples
javahtmlunit

HtmlUnit onclick execution download file


So here's the deal:
I am accessing some webpage(using HtmlUnit) on which there's a button. I programatically click that button(big thanks to Mads Hansen)

List l = page.getByXPath( "//input[@type='submit' and @value='Save as XML']" );
((HtmlSubmitInput)l.get(0)).click();

The button has an onclick event, following:

onclick="document.forms[0].action="calcSaveXML_BG#POS";document.forms[0].submit()"

When I click that button normally through the browser, I am given the chance to save a xml file on my hard drive.
The thing is, I want to be able to get that xml file programatically. Can this be done?


Solution

  • Ok I figured that out. In case someone's interested:

    List l = page.getByXPath( "//input[@type='submit' and @value='Save as XML']" );
    XmlPage result = ((HtmlSubmitInput)l.get(0)).click();
    String xml = result.getContent();
    
    try
    {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse( new java.io.ByteArrayInputStream( xml.getBytes( "UTF-8" ) ) );
        doc.getDocumentElement().normalize();
        //actual work going here
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }