Ktor: ContentType for HttpClient request

Created on 10 Oct 2018  路  9Comments  路  Source: ktorio/ktor

how to setup contentType for HttpClient request?

    val client = HttpClient(OkHttp) {
        engine {
            defaultRequest {
                contentType(ContentType.Application.FormUrlEncoded)
            }
        }
    }

this code throws exception:
io.ktor.http.UnsafeHeaderException: Header Content-Type is controlled by the engine and cannot be set explicitly

ux

Most helpful comment

Sure :)

val response = client.call(url) {
   method = HttpMethod.Post
   body = TextContent(json.writeValueAsString(userData), contentType = ContentType.Application.Json)
}.response

All 9 comments

Hi, @coolemza. Thanks for the report.
You could set up it in OutgoingContent

@e5l Please, provide an example of content type setting for particular request (rather client).

That is this fragment does work with 0.9.3, but not with > 0.9.3:

            val response = client.call(url) {
                contentType(ContentType.Application.Json)
                method = HttpMethod.Post
                body = json.writeValueAsString(userData)
            }.response

Sure :)

val response = client.call(url) {
   method = HttpMethod.Post
   body = TextContent(json.writeValueAsString(userData), contentType = ContentType.Application.Json)
}.response

@soywiz could we have a sample for the case?

is it possible to set default content type for engine?

Yep. You could intercept send pipeline and wrap the body into outgoing content with selected ContentType field.

I think the problem is obsolete for now. Closed

@e5l What if you don't want to specify a Content-Type? There's this scenario with direct uploads to Google Cloud Storage Buckets where adding a Content-Type header results in a signature mismatch. Here's more info about this.

The following also fails because it sets Content-Type: null:

client.put<String> {
    url(url)
    body = ByteArrayContent(byteArray, contentType = null)
}
Was this page helpful?
0 / 5 - 0 ratings