okhttpmockwebserver

How can I send a streamed response using OkHttp's mockwebserver?


The typical flow when returning the contents of file from a server back to the client are to:

1.) Obtain an inputstream to the file 2.) Write chunks of the stream to the open socket 3.) Close the input stream

When using OkHttp's mockwebserver the MockResponse only accepts a Okio buffer. This means we must read the entire input stream contents into the buffer before sending it. This will probably result in an OutOfMemory exception if the file is too large. Is there a way to accomplish the logic flow I outlined above without using a duplex response or should I use another library? Here's how I'm currently sending the file in kotlin:

 val inputStream = FileInputStream(file)

 val source = inputStream.source()

 val buf = Buffer()
 buf.writeAll(source.buffer())

 source.close()

 val response = HTTP_200
 response.setHeader("Content-Type", "video/mp4")
 response.setBody(buf)

 return response
 // Dispatch the response, etc...

Solution

  • This is a design limitation of MockWebServer, guaranteeing that there’s no IOExceptions on the serving side. If you have a response that's bigger than you can keep in-memory, MockWebServer is the wrong tool for the job.