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

Hep*_*tus 6 java okhttp3

正在使用okhttp3到Web 服务器POSTJSON有效负载。我们想知道请求的总字节数和请求的响应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();
Run Code Online (Sandbox Code Playgroud)

这是 a 的完整字节数POST吗?

Yur*_*mke 0

您可以调整 HttpLoggingInterceptor 中的代码,该代码缓冲流式请求和响应以获取其大小,即使提前未知也是如此。

https://github.com/square/okhttp/blob/b97eeacaa31a2c72a9396f5a4eab82f69b39cda8/okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt

  • 链接不起作用,也许应该使用一些代码示例进行编辑,或者解释如何获取有用的源代码以使其有用。 (5认同)