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

Viewed 4152

Were using okhttp3 to POST a JSON payload to a web server. We want to know the total byte count of the request and the response for the POST request. Ultimately, we want to get the data throughput. Here is the code:

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();

Is this the complete byte count for a POST?

2 Answers

If you are happy with an estimate, you can use EventListener for this

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
        }
Related