在 Java 中获取 HTTP 响应的大小
我想知道响应某个 http 请求发送了多少数据。 我目前所做的是:
HttpURLConnection con = (HttpURLConnection) feedurl.openConnection();
//检查内容大小的响应 int feedsize = con.getContentLength();
问题是,内容长度并不总是被设置。例如,当服务器使用transfer-encoding=chunked 时,我得到的值为-1。
我不需要需要它来显示进度信息。我只需要知道完成后发送给我的数据的大小。
背景:我需要此信息,因为我想将其与使用 gzip 编码发送的响应的大小进行比较。
I would like to know how much data was sent in response to a certain http-request.
What I currently do is this:
HttpURLConnection con = (HttpURLConnection) feedurl.openConnection();
//check the response for the content-size
int feedsize = con.getContentLength();
The problem is, that content-legnth is not always set. E.g. when the server uses transfer-encoding=chunked I get back a value of -1.
I do not need this to display progress information. I just need to know the size of the data that was sent to me after it has been done.
Background: I need this information because I would like to compare it to the size of a response, that was sent using gzip encoding.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会使用 commons-io CountingInputStream,这将为您完成这项工作。一个完整但琐碎的例子:
I'd use a commons-io CountingInputStream, which would do the job for you. A full but trivial example:
您可以扩展
FilterInputStream
,覆盖read()
、read(byte[],int,int)
和skip 方法,以便在调用
super
表单后,它们会用读取的字节数更新计数器。然后用其中之一包装
URLConnection
返回的输入流,并使用包装器代替原始流。完成后,您可以查询包装器的计数器。其他(“手动”)方法是使用 YSlow 等工具在浏览器中收集统计信息,或使用 Wireshark 来检查网络流量。
You can extend
FilterInputStream
, overriding theread()
,read(byte[],int,int)
, andskip
methods so that after calling thesuper
form, they update a counter with the number of bytes read.Then wrap the input stream returned by
URLConnection
with one of these, and use the wrapper in place of the original stream. When you're done, you can query wrapper's its counter.Other ("manual") approaches would be use a tool like YSlow to gather statistics in a browser, or Wireshark to examine the traffic on the network.