Search code examples
androidhttpokhttpbandwidth

Is there a way to figure out content download time in OkHttp?


I'm trying to calculate the network bandwidth in my Android app. How do I figure out the response download time (not including the turn around time for my HTTP request) using OkHttp3 library?

In my Application level interceptor, I have access to Response and I see properties like sentRequestAtMillis and receivedResponseAtMillis. And I think following equation is not accurate for my case since:

receivedResponseAtMillis - sentRequestAtMillis = requestSendTime + Server Latency + responseDownloadTime

So I'm trying to figure out is there a way I can take Server latency & requestSendTime, out of this equation and can just get responseDownloadTime?

I have tried taking a timestamp right after I call chain.proceed(request):


        Request request = chain.request();
        Response response = chain.proceed(request);
        String url = request.url().toString();

        long currentTimeMillis = System.currentTimeMillis();

        double contentDownloadTimeInSecs = (currentTimeMillis - response.receivedResponseAtMillis()) / 1000.0;

        double requestRoundTripTimeInSecs = (currentTimeMillis - response.sentRequestAtMillis()) / 1000.0;


    }

I thought of this only because in the documentation of
receivedResponseAtMillis() https://square.github.io/okhttp/3.x/okhttp/okhttp3/Response.html#receivedResponseAtMillis-- I read that it is the timestamp immediately taken when the headers of the response are received from the network. So maybe subtracting the way I have shown in the above code snippet, I can get the response download time?

When I throttle my App using throttling softwares like, NetworkLinkConditioner. I'm seeing inconsistent values based on the mechanism I'm using above. So not really sure whether this is the right way to achieve this.

Please help in validating my theory, I would really appreciate if someone can talk about how to capture contentDownloadTime using OkHttp or whether its not possible at all.

Thank you


Solution

  • Take a look at OkHttp’s EventListener, which is triggered for many of the interesting events in your HTTP call. You can use it if you like, or an interceptor, both of which can record the system clock when something of interest occurs.