[kotlin] Map file and binary to ByteArray (#19840)

* [kotlin] Map file and binary to ByteArray

* [kotlin] Map file and binary to ByteArray
This commit is contained in:
Bruno Coelho
2024-10-11 08:59:16 +01:00
committed by GitHub
parent 185c0639c0
commit 462f450366
26 changed files with 358 additions and 5 deletions

View File

@@ -58,6 +58,21 @@ open class ApiClient(val baseUrl: String, val client: Call.Factory = defaultClie
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
}
/**
* Guess Content-Type header from the given byteArray (defaults to "application/octet-stream").
*
* @param byteArray The given file
* @return The guessed Content-Type
*/
protected fun guessContentTypeFromByteArray(byteArray: ByteArray): String {
val contentType = try {
URLConnection.guessContentTypeFromStream(byteArray.inputStream())
} catch (io: IOException) {
"application/octet-stream"
}
return contentType
}
/**
* Guess Content-Type header from the given file (defaults to "application/octet-stream").
*
@@ -71,6 +86,7 @@ open class ApiClient(val baseUrl: String, val client: Call.Factory = defaultClie
protected inline fun <reified T> requestBody(content: T, mediaType: String?): RequestBody =
when {
content is ByteArray -> content.toRequestBody((mediaType ?: guessContentTypeFromByteArray(content)).toMediaTypeOrNull())
content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull())
mediaType == FormDataMediaType ->
MultipartBody.Builder()