Question

I have some code that does a bunch of HTTP GETs, POSTs, and PUTs using Commons HttpClient 3.1. I'd like to provide a current transfer speed indicator in my GUI, but was unable to find any methods for determining the transfer rate of a HttpMethod being processed.

I could easily just time the transfer and do some simple math after it was complete to determine what the speed was, but this provides a bad user experience during a long upload or download. Does anyone know how to determine the transfer rate of a Commons HttpClient request while it is still being processed?

Was it helpful?

Solution

I haven't used HttpClient extensively, so there may be a simple hook. However, it appears that HttpConnection.getResponseInputStream() returns a simple InputStream.

To add the hook yourself, you'd need to override HttpConnectionManager and HttpConnection, to return a decorated stream that keeps track of the number of bytes read. You could then spin up a second thread to poll this stream and display the transfer rate, or (better) create the stream with a callback every N bytes (better because you don't have to care about concurrency, and you can also set N such that the callback is only invoked for large files).

OTHER TIPS

Simpler hook would be to extend the HttpEntityWrapper and override the getContent() method:

public InputStream getContent() throws IOException {
    InputStream wrappedin = wrappedEntity.getContent();
    return new MyTransferRateInputStream(wrappedin);
}

Later you can add this as the response interceptor

httpClient.addResponseInterceptor(HttpResponseInterceptor itcp)

That way you don't need to override the mentioned HttpConnectionManager and HttpConnection

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top