[kotlin][client] support text/plain in okhttp (#20250)

* refactor: simplify application/octet-stream check

* feat: support text/plain in kotlin okhttp client

* refactor: remove redundant always-false condition

content is ByteArray is checked earlier
This commit is contained in:
Kirill Romanov
2024-12-05 06:51:10 +03:00
committed by GitHub
parent 8a07557865
commit 05d4aa9f62
23 changed files with 135 additions and 89 deletions

View File

@@ -41,6 +41,7 @@ open class ApiClient(val baseUrl: String, val client: Call.Factory = defaultClie
protected const val FormUrlEncMediaType: String = "application/x-www-form-urlencoded"
protected const val XmlMediaType: String = "application/xml"
protected const val OctetMediaType: String = "application/octet-stream"
protected const val TextMediaType: String = "text/plain"
val apiKey: MutableMap<String, String> = mutableMapOf()
val apiKeyPrefix: MutableMap<String, String> = mutableMapOf()
@@ -169,10 +170,10 @@ open class ApiClient(val baseUrl: String, val client: Call.Factory = defaultClie
.toRequestBody((mediaType ?: JsonMediaType).toMediaTypeOrNull())
}
mediaType == XmlMediaType -> throw UnsupportedOperationException("xml not currently supported.")
mediaType == OctetMediaType && content is ByteArray ->
content.toRequestBody(OctetMediaType.toMediaTypeOrNull())
mediaType == TextMediaType && content is String ->
content.toRequestBody(TextMediaType.toMediaTypeOrNull())
// TODO: this should be extended with other serializers
else -> throw UnsupportedOperationException("requestBody currently only supports JSON body, byte body and File body.")
else -> throw UnsupportedOperationException("requestBody currently only supports JSON body, text body, byte body and File body.")
}
@OptIn(ExperimentalStdlibApi::class)
@@ -243,7 +244,8 @@ open class ApiClient(val baseUrl: String, val client: Call.Factory = defaultClie
Serializer.moshi.adapter<T>().fromJson(bodyContent)
}
mediaType == OctetMediaType -> body.bytes() as? T
else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.")
mediaType == TextMediaType -> body.string() as? T
else -> throw UnsupportedOperationException("responseBody currently only supports JSON body, text body and byte body.")
}
}