Skip to content

Commit

Permalink
KTOR-5971 Set ContentType for ByteArrayContent body in OkHttp (#3653)
Browse files Browse the repository at this point in the history
  • Loading branch information
marychatte authored Jun 13, 2023
1 parent c2d8a21 commit 4bd7334
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ import io.ktor.util.date.*
import io.ktor.utils.io.*
import kotlinx.coroutines.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.internal.http.HttpMethod
import okio.*
import java.io.*
import java.io.Closeable
import java.util.concurrent.*
import kotlin.coroutines.*
Expand Down Expand Up @@ -62,7 +62,6 @@ public class OkHttpEngine(override val config: OkHttpConfig) : HttpClientEngineB
client.connectionPool.evictAll()
client.dispatcher.executorService.shutdown()
}
@Suppress("BlockingMethodInNonBlockingContext")
(dispatcher as Closeable).close()
}
}
Expand Down Expand Up @@ -206,7 +205,7 @@ private fun HttpRequestData.convertToOkHttpRequest(callContext: CoroutineContext
@OptIn(DelicateCoroutinesApi::class)
internal fun OutgoingContent.convertToOkHttpBody(callContext: CoroutineContext): RequestBody = when (this) {
is OutgoingContent.ByteArrayContent -> bytes().let {
it.toRequestBody(null, 0, it.size)
it.toRequestBody(contentType.toString().toMediaTypeOrNull(), 0, it.size)
}
is OutgoingContent.ReadChannelContent -> StreamRequestBody(contentLength) { readFrom() }
is OutgoingContent.WriteChannelContent -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package io.ktor.client.engine.okhttp
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.client.tests.utils.*
import io.ktor.http.*
import io.ktor.http.content.*
Expand Down Expand Up @@ -123,4 +124,25 @@ class RequestTests : TestWithKtor() {
}
}
}

@Test
fun testFormContentType() = testWithEngine(OkHttp) {
config {
engine {
addInterceptor { chain ->
val request = chain.request()
val contentType = request.body?.contentType()
assertEquals(ContentType.Application.FormUrlEncoded.contentType, contentType?.type)
assertEquals(ContentType.Application.FormUrlEncoded.contentSubtype, contentType?.subtype)
chain.proceed(request)
}
}
}

test { client ->
client.post("$testUrl/echo") {
setBody(FormDataContent(formData = Parameters.build {}))
}
}
}
}

0 comments on commit 4bd7334

Please sign in to comment.