获取Java中的HTTP响应大小 [英] Get Size of HTTP Response in Java

查看:803
本文介绍了获取Java中的HTTP响应大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道响应某个http请求发送了多少数据。
我目前做的是:

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

//检查内容大小的响应
int feedsize = con.getContentLength( );

//check the response for the content-size int feedsize = con.getContentLength();

问题是,内容-ththnth并不总是设置。例如。当服务器使用transfer-encoding = chunked时,我得到一个值-1。

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.

背景:我需要这些信息,因为我想将它与使用gzip编码发送的响应大小。

Background: I need this information because I would like to compare it to the size of a response, that was sent using gzip encoding.

推荐答案

我使用 commons-io CountingInputStream ,它可以帮到你。一个完整而简单的例子:

I'd use a commons-io CountingInputStream, which would do the job for you. A full but trivial example:

public long countContent(URL feedurl) {
  CountingInputStream counter = null;
  try {
     HttpURLConnection con = (HttpURLConnection) feedurl.openConnection();
     counter = new CountingInputStream(con.getInputStream());
     String output = IOUtils.toString(counter);
     return counter.getByteCount();
  } catch (IOException ex) {
     throw new RuntimeException(ex);
  } finally {
     IOUtils.closeQuietly(counter);
  }
}

这篇关于获取Java中的HTTP响应大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆