繁体   English   中英

OKHTTP:如何测量请求和响应中的总字节数?

[英]OKHTTP: How to measure total bytes in Request and Response?

正在使用okhttp3POST有效负载发布到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中的代码,该代码缓冲流请求和响应以获取其大小,即使提前未知也是如此。

https://github.com/square/okhttp/blob/master/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.java

如果您对估计感到满意,您可以为此使用 EventListener

https://square.github.io/okhttp/features/events/

https://github.com/google/horologist/blob/main/network-awareness/src/main/java/com/google/android/horologist/networks/okhttp/impl/NetworkLoggingEventListenerFactory.kt#L98-L120

        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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM