Get HTTP response size in Java

I would like to know how much data was sent in response to a specific http request. What I'm doing right now is:

   HttpURLConnection con = (HttpURLConnection) feedurl.openConnection();

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

The problem is that content-legnth is not always set. For example. when the server uses transfer-encoding = chunked, I return a value of -1.

I need not to display progress information. I just need to know the size of the data that was sent to me after it was done.

Reference Information. I need this information because I would like to compare it with the size of the response that was sent using gzip encoding.

+5
source share
2 answers

I would use commons-io CountingInputStream , which would do the job for you. A complete 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);
  }
}
+8
source

You can expand FilterInputStreamby overriding the methods read(), read(byte[],int,int)and skipso that after calling the form superthey update the counter with the number of bytes read.

Then terminate the input stream returned by URLConnectionone of them and use a wrapper instead of the original stream. When you're done, you can request a wrapper with your counter.

( "" ) YSlow Wireshark .

+2

All Articles