如何在 Commons HttpClient 3.x 中获取当前传输速率
我可以轻松地计算传输时间并在完成后进行一些简单的数学计算以确定速度,但这在长时间上传或下载期间提供了糟糕的用户体验。有谁知道如何确定 Commons HttpClient 请求在处理过程中的传输速率?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我没有广泛使用 HttpClient,所以可能有一个简单的钩子。但是,似乎 HttpConnection.getResponseInputStream() 返回一个简单的
InputStream
。要自己添加挂钩,您需要重写 HttpConnectionManager 和 HttpConnection,以返回一个跟踪读取字节数的修饰流。然后,您可以启动第二个线程来轮询该流并显示传输速率,或者(更好)每 N 个字节创建一个带有回调的流(更好,因为您不必关心并发性,并且您还可以设置 N这样回调只会针对大文件调用)。
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
andHttpConnection
, 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).更简单的钩子是扩展
HttpEntityWrapper
并覆盖getContent()
方法:稍后您可以将其添加为响应拦截器
这样您就不需要覆盖提到的
HttpConnectionManager
和HttpConnection
Simpler hook would be to extend the
HttpEntityWrapper
and override thegetContent()
method:Later you can add this as the response interceptor
That way you don't need to override the mentioned
HttpConnectionManager
andHttpConnection