Reputation: 745
I am downloading a file from the web via HtmlUnit. This is what my (working) code looks like:
Page dlPage = client.getPage(url);
FileOutputStream fos = new FileOutputStream(destinationFile);
try
{
IOUtils.copy(dlPage.getWebResponse().getContentAsStream(), fos);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
fos.close();
}
I want to show the download progress. Therefore I need to know the file size. The Content-Length header is sent by the server but the problem is that I can read the headers after the file is downloaded. the getPage()
method is blocking until the file is downloaded.
Is there any way to read just the response headers first in HtmlUnit and then the content? Or is there any other way to solve this problem?
Thanks!
Upvotes: 1
Views: 287
Reputation: 745
Okay, I figured out a way to get this working: Before the download I send a HEAD request to the server so I can use the response to read the content length:
WebRequest wr = new WebRequest(new URL(url), HttpMethod.HEAD);
Page wrPage = client.getPage(wr);
long contentLength = Integer.valueOf(wrPage.getWebResponse().getResponseHeaderValue("Content-Length"));
System.out.println(contentLength);
Upvotes: 1
Reputation: 790
You can use getContentLength() method of URLConnection to get the length when the connection is established.
Upvotes: 3