gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:17:20 24 4
gpt4 key购买 nike

正在使用 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 的完整字节数吗?

最佳答案

如果您对估算结果满意,可以为此使用 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
}

关于java - OKHTTP:如何测量请求和响应中的总字节数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45075404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com