Conteggio byte inviati / ricevuti su HTTP
Domanda
In Java,
Come si possono contare i byte inviati e ricevuti tramite una connessione HTTP attiva?
Voglio visualizzare alcune statistiche come:
Bytes Sent : xxxx Kb
Bytes Received : xxxx Kb
Duration : hh:mm
Soluzione
È difficile vedere come potresti decorare HttpConnection per contare i dati byte grezzi. Potresti reimplementare HTTP usando i socket, ma questo dovrebbe essere abbastanza importante per fare queste lunghezze.
Esempio di risposta da 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....
Le richieste HTTP sono ragionevolmente semplici, quindi potresti provare a ricostruirlo usando le informazioni esposte. Qualcosa del modulo:
// 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);
Tale implementazione è incompleta e non testata. Dovresti studiare i dettagli del protocollo HTTP per garantire l'accuratezza del tuo risultati.
Altri suggerimenti
Avvolgi getInputStream () e getOutputStream () di HTTPURLConnection nei tuoi flussi che contano i byte che li attraversano. O ancora meglio usare la libreria IO di Apache Commons: hanno contando le implementazioni dei flussi lì dentro.