简体   繁体   English

HtmlUnit:确定文件大小

[英]HtmlUnit: Determine file size

I am downloading a file from the web via HtmlUnit. 我正在通过HtmlUnit从Web下载文件。 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. Content-Length标头是由服务器发送的,但问题是下载文件后我可以读取标头。 the getPage() method is blocking until the file is downloaded. 在下载文件之前, getPage()方法一直处于阻塞状态。

Is there any way to read just the response headers first in HtmlUnit and then the content? 有什么方法可以先在HtmlUnit中读取内容,然后再读取内容? Or is there any other way to solve this problem? 还是有其他方法可以解决此问题?

Thanks! 谢谢!

您可以使用URLConnection的 getContentLength()方法获得建立连接时的长度。

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: 好的,我想出了一种方法来完成此工作:在下载之前,我向服务器发送了HEAD请求,以便可以使用响应读取内容长度:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM