Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Size of HTTP Response in Java

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.

like image 844
er4z0r Avatar asked Nov 04 '09 14:11

er4z0r


1 Answers

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);
  }
}
like image 195
Jim Downing Avatar answered Oct 10 '22 14:10

Jim Downing