HttpClient
- Kotlin course
- Advanced
- Lesson 14/83
- 5 min
Learn HttpClient configuration.
HttpClient configuration
When you create an HttpClient you can open a config block and add plugins. The most common plugin is ContentNegotiation, which handles JSON serialization automatically.
Example: HttpClient { install(ContentNegotiation) { json() } }. This block turns a JSON body into a Kotlin object automatically. Plugins are added with the install function. To switch engine you call HttpClient(CIO) { ... }. Central configuration means all requests share the same behavior.
JSON with ContentNegotiation
ContentNegotiation is the plugin that turns HTTP bodies into Kotlin objects automatically. With json() it uses kotlinx.serialization.
Once this plugin is added, client.get<User>(url) returns a User object directly. The body no longer needs manual parsing. The same applies to client.post bodies, which are serialized automatically. The plugin picks the format by looking at the Content-Type header: application/json for JSON, application/xml for XML.
Practice Configure HttpClient and print
Configure the client with HttpClient { install(ContentNegotiation) { json() } }. Print println("Configured"), then close with client.close().
Starter code
// HttpClient configuration
// write here
import io.ktor.client.*
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
fun main() {
}Sample solution
fun main() {
val client = HttpClient {
install(ContentNegotiation) { json() }
}
println("Configured")
client.close()
}Expected output
Configured
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the install call
HttpClient {
____(ContentNegotiation) { json() }
}
HttpClient {
install(ContentNegotiation) { json() }
}
Explanation: answer: install. Plugins are added with install.
2 Match HttpClient plugins
| Term | Meaning |
|---|---|
ContentNegotiation |
Converts JSON |
install |
Adds plugin |
json() |
Picks format |
HttpClient |
Client |
3 Which function adds a plugin to HttpClient?
- use
- install Correct answer
- with
- add
Explanation: answer: install. Plugins are added with install.