https://kotlinlang.org logo
#ktor
Title
# ktor
n

natario1

03/28/2022, 11:04 PM
Hi, 2.0 question - with 1.X we’re able to upload an image as follows:
Copy code
contentType(ContentType.Image.JPEG)
setBody(byteArray)
But in 2.0, I get a 500 error. Has anything changed with respect to this?
a

Aleksei Tirman [JB]

03/29/2022, 8:16 AM
No. Just the
body
property is replaced with the
setBody
method.
n

natario1

03/29/2022, 12:10 PM
Thanks! Apparently there's a bug with contentType being erased if you install the negotiation plugin, which makes the server refuse the request.
a

Aleksei Tirman [JB]

03/29/2022, 12:16 PM
Could you please share a code snippet to reproduce this bug?
n

natario1

03/29/2022, 2:04 PM
Copy code
val ktor = ktorClient
val image = imageFile.readBytes()
<http://ktor.post|ktor.post>(serverUrl) {
    contentType(ContentType.Image.JPEG)
    setBody(thumb)
}
It’s not really erased but it’s changed from
image/jpeg
which I explicitly set, to
application/octet-stream
. This didn’t happen in 1.X and also does not happen if I don’t apply the content negotiation plugin
I think application/octet-stream is the default for byte arrays, so since the plugin removes the header ( https://youtrack.jetbrains.com/issue/KTOR-3655 ), ktor ends up overriding it. I understand from KTOR-3655 that this is not considered a bug, but then how would I make this request? Currently using a separate client just for this endpoint
a

Aleksei Tirman [JB]

03/29/2022, 3:24 PM
In the following code the
Content-Type
header with the value
application/octet-stream
is sent even when the
ContentNegotiation
plugin is installed:
Copy code
import io.ktor.client.*
import io.ktor.client.engine.apache.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*

suspend fun main() {
    val client = HttpClient(Apache) {
        install(ContentNegotiation) {
            json()
        }
    }

    val r = <http://client.post|client.post>("<https://httpbin.org/post>") {
        contentType(ContentType.Application.OctetStream)
        setBody(ByteArray(1024))
    }.bodyAsText()
    println(r)
}
n

natario1

03/29/2022, 3:27 PM
Right so now if you change it to ContentType.Image.JPEG which is what my server expects, you should see that it gets overwritten (version 2.0.0-beta1)
a

Aleksei Tirman [JB]

03/29/2022, 3:28 PM
I got it. Thank you.
👍 1
n

natario1

03/29/2022, 3:29 PM
In case the underlying engine makes a difference, I’m using OkHttp on Android with default configuration
a

Aleksei Tirman [JB]

03/29/2022, 3:29 PM
I don’t think so. I’ve reproduced it with the
Apache
engine.
I’ve created this issue to address the problem with ContentNegotiation plugin.
n

natario1

03/29/2022, 3:54 PM
Thanks!