开发者

How to get current Transfer Rate in Commons HttpClient 3.x

开发者 https://www.devze.com 2022-12-12 02:43 出处:网络
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

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 provide开发者_开发知识库s 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?


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).


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

0

精彩评论

暂无评论...
验证码 换一张
取 消