I need to download a file after button click, using selenium's htmlunit in java. The issue i am having is, after simulating the button click, the downloaded content returns the entire html instead of the actual file. Below are the steps i am following:
In my html/javascript,i have created the functionality to upload and download json using separate buttons as shown below. It works as expected in any web browser(chrome/firefox/ie)
upload button
<button id="loadJson" class="button" onclick="$('#upload').click()" title="Reload JSON"></button>
<form enctype="multipart/form-data" id="upload-form" style="display: none">
<input id="upload" type=file accept=".json" name="files[]" size=30></form>
download button:(download dialogbox opens for specifying file name and save location)
<button id="saveJson" class="button" onclick="testUtil.save()" title="Save JSON"></button>
I am simulating the upload in htmlunit using the following code below:
String webUrl="http://localhost:8000/";
HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME);
WebClient webClient = new WebClient();
webClient.getOptions().setJavaScriptEnabled(false);
HtmlPage page = webClient.getPage(webUrl);
System.out.println(page.getByXPath(".//*[@id='upload']").get(0).toString());
HtmlFileInput input =(HtmlFileInput) page.getByXPath(".//*[@id='upload']").get(0);
input.setValueAttribute("C:\\My_files\\test.json");
Afterwards, I want to download the file i have uploaded,
HtmlButton button= (HtmlButton) page.getByXPath(".//*[@id='saveJson']").get(0);
System.out.println(button.toString());
to verify if i've selected the input: i see this as the output from the print statement above
HtmlButton[<button id="saveJson" class="button" onclick="testUtil.save()"
title="Save JSON">]
then i try to download and save :
InputStream is = button.click().getWebResponse().getContentAsStream();
byte[] buffer = new byte[is.available()];
is.read(buffer);
File targetFile = new File("C:\\My_files\\new.json");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
When i view the output file,it doesn't return the json,but it just returns the content of the html page(index.html). I am really not sure what i am missing.
Can anyone who has experience with selenium htmlunitdriver,please guide with debugging this issue?