views:

269

answers:

2

In Java,
How could the bytes sent and received over an active HTTP connection be counted?
I want to display some statistics like:

Bytes Sent     : xxxx Kb   
Bytes Received : xxxx Kb  
Duration       : hh:mm
+1  A: 

Wrap the HTTPURLConnection's getInputStream() and getOutputStream() in your own streams that count the bytes that go through them. Or even better use the Apache Commons IO library - they have counting stream implementations in there.

CarlG
+1  A: 

It is difficult to see how you could decorate HttpConnection to count the raw byte data. You could reimplement HTTP using sockets, but this would have to be pretty important to go to those lengths.

Sample response from stackoverflow.com:

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Expires: Mon, 21 Sep 2009 11:46:48 GMT
Vary: Accept-Encoding
Server: Microsoft-IIS/7.0
Date: Mon, 21 Sep 2009 11:46:48 GMT
Content-Length: 19452

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
                      "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head>...remaining data....

HTTP requests are reasonably simple, so you might try reconstructing it using the information that is exposed. Something of the form:

// TODO: edge cases, error handling, header delimiter, etc.
int byteCount = 0;
int headerIndex = 0;
while (true) {
  String key = httpConnection.getHeaderFieldKey(headerIndex);
  if (key == null)
    break;
  String value = httpConnection.getHeaderField(headerIndex++);
  byteCount += key.getBytes("US-ASCII").length
      + value.getBytes("US-ASCII").length + 2;
}
byteCount += httpConnection.getHeaderFieldInt("Content-Length",
    Integer.MIN_VALUE);

That implementation is incomplete and untested. You'd need to study up on the details of the HTTP protocol to ensure the accuracy of your results.

McDowell