mirror of
https://github.com/OpenAPITools/openapi-generator.git
synced 2025-12-04 11:26:09 +00:00
[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:
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user