Contando bytes enviados / recibidos a través de HTTP
Pregunta
En Java,
¿Cómo podrían contarse los bytes enviados y recibidos a través de una conexión HTTP activa?
Quiero mostrar algunas estadísticas como:
Bytes Sent : xxxx Kb
Bytes Received : xxxx Kb
Duration : hh:mm
Solución
Es difícil ver cómo decorar HttpConnection para contar los datos de bytes sin procesar. Puede volver a implementar HTTP utilizando sockets, pero esto tendría que ser bastante importante para llegar a esas longitudes.
Respuesta de muestra de 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">
<html>
<head>...remaining data....
Las solicitudes HTTP son razonablemente simples, por lo que puede intentar reconstruirlas utilizando la información que se expone. Algo de la forma:
// 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);
Esa implementación está incompleta y no se ha probado. Debería estudiar los detalles del protocolo HTTP para garantizar la precisión de su resultados.
Otros consejos
Envuelva getInputStream () y getOutputStream () de HTTPURLConnection en sus propios flujos que cuentan los bytes que los atraviesan. O incluso mejor usar la biblioteca Apache Commons IO: tienen implementaciones de flujo de conteo allí.