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

时间:2017-07-13 08:31:56

标签: java okhttp3

okhttp3 POST JSON个有效负载用于Web服务器。我们想知道请求的总字节数和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的完整字节数吗?

1 个答案:

答案 0 :(得分:1)

您可以调整HttpLoggingInterceptor中的代码,该代码会缓冲流请求和响应以获取其大小,即使事先不知道也是如此。

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