![](/img/trans.png)
[英]How to measure the download speed using bytes_downloaded and bytes_total Android / Java
[英]OKHTTP: How to measure total bytes in Request and Response?
正在使用okhttp3
将POST
有效负载发布到JSON
服务器。 我们想知道请求的总字节数和POST
请求的响应。 最终,我们希望获得数据吞吐量。 这是代码:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
mBytesSent += request.body.contentLength(); // Payload byte count
mBytesSent += request.headers().size();
mBytesSent += request.tag().toString().length();
Response response = client.newCall(request).execute()
mBytesRecd += response.body().contentLength();
mBytesRecd += response.headers().toString().length();
mBytesRecd += response.message().length();
这是POST
的完整字节数吗?
您可以调整HttpLoggingInterceptor中的代码,该代码缓冲流请求和响应以获取其大小,即使提前未知也是如此。
如果您对估计感到满意,您可以为此使用 EventListener
https://square.github.io/okhttp/features/events/
override fun requestHeadersEnd(call: Call, request: Request) {
bytesTransferred += request.headers.byteCount()
}
override fun requestBodyEnd(call: Call, byteCount: Long) {
bytesTransferred += byteCount
}
override fun responseHeadersEnd(call: Call, response: Response) {
bytesTransferred += response.headers.byteCount()
}
override fun responseBodyEnd(call: Call, byteCount: Long) {
bytesTransferred += byteCount
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.