morristech
3/29/2019 - 7:53 AM

Implementation of OkHttp's RequestBody that supports Android's content:// URIs

Implementation of OkHttp's RequestBody that supports Android's content:// URIs

import android.content.ContentResolver
import android.net.Uri
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.BufferedSink
import okio.Okio
import java.lang.IllegalStateException

class ContentUriRequestBody(
        private val contentResolver: ContentResolver,
        private val contentUri: Uri
) : RequestBody() {

    override fun contentType(): MediaType? {
        val contentType = contentResolver.getType(contentUri) ?: return null
        return MediaType.parse(contentType)
    }

    override fun writeTo(sink: BufferedSink) {
        val inputStream = contentResolver.openInputStream(contentUri) 
                ?: throw IllegalStateException("Couldn't open content URI for reading: $contentUri")
        
        Okio.source(inputStream).use { source ->
            sink.writeAll(source)
        }
    }
}