What is the easiest way to reader entire byteStream/inputStream response into memory in OkHttp?

Viewed 38

Relatively new to both Kotlin and OkHttp. Currently have the following code

class CustomWebViewClient : WebViewClient() {
    override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
        val okClient: OkHttpClient = OkHttpClient()

        val okRequest: Request = Request.Builder().url(request!!.url.toString()).build()

        val response = okClient.newCall(okRequest).execute()

        return WebResourceResponse("", "", response.body!!.byteStream())
        
        // cant call response.close() otherwise the above return object breaks
    }
}

Having trouble with trying to call response.close() because it breaks my byteStream()

What is the easiest way to read the entire contents of the response into an internal byte array/in-memory input stream?

(Before subsequently closing the connection, and passing the in-memory copy of the input stream to the response?)

2 Answers

Try one of these:

response.body().bytes() response.body().string()

I just ended up wrapping the results in an ByteArrayInputStream(...) call. This solution worked for me.

class CustomWebViewClient : WebViewClient() {
    override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
        val okClient: OkHttpClient = OkHttpClient()

        val okRequest: Request = Request.Builder().url(request!!.url.toString()).build()

        val response = okClient.newCall(okRequest).execute()

        val result = WebResourceResponse("", "", ByteArrayInputStream(response.body!!.bytes()))

        response.close()

        return result
    }
}
Related