Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Implementation of OkHttp's RequestBody that supports Android's content:// URIs
import android.content.ContentResolver
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 ->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.