Search code examples
okhttpokio

okhttp - execute() vs body().byteStream


When using OkHttp, the network request is executed in 1 or 2 in the following code:

            val response = client.newCall(request).execute() // (1)
            if (response.isSuccessful) {
                val bs = response.body().byteStream() // (2)
                val bitmap = BitmapFactory.decodeStream(bs)
            } else { ... }

I always thought I was executed in (1), in which case it makes sense to ask if the response was successful. But today I decided to implement this official recipe to track the progress of the file being downloaded.

Then I realised, that if I deleted the lines (response.body().byteStream()), the progress counter doesn't move at all. In theory, we are not downloading anything, except we are or else what does success mean in this scenario.

I'm sorry if this is a dummy question, I believe there's something very fundamental about networking that I'm missing here, and I would like to learn more. I tried to understand the source code for the Okiolibrary but it's a little too complex for me, I would need some reference or guidance.


Solution

  • There’s four steps to each OkHttp call:

    1. Write the request headers
    2. Stream the request body, if it exists
    3. Read the response headers
    4. Stream the response body

    When you call execute() OkHttp does steps 1 – 3. Further calls stream the response body. If your response body is large this allows you to start decoding the response while it's still downloading.