HTTP Client Requests

Estimated reading time: 5 minutes

Simple requests

The basic usage is super simple: you just have to instantiate an HttpClient instance, specifying an engine, for example Apache, OkHttp, Android, Ios, Jetty or CIO, and start making requests using one of the many convenience methods available.

Since Ktor 0.9.3, you can omit the engine, and Ktor will choose an engine among the ones that are available from the included artifacts using a ServiceLoader.

First you need to instantiate the client:

val client = HttpClient(Apache)

Then, to perform a GET request fully reading a String:

val htmlContent = client.get<String>("")

And in the case you are interested in the raw bits, you can read a ByteArray:

val bytes: ByteArray ="").response.readBytes()

It is possible to customize the request a lot and to stream the request and response payloads, but you can also just call a convenience extension method like HttpClient.get to do a GET request to receive the specified type directly (for example String).

Custom requests

We cannot live only on get requests, Ktor allows you to build complex requests with any of the HTTP verbs, with the flexibility to process responses in many ways.

The call method

The HttpClient call method, returns an HttpClientCall and allows you to perform simple untyped requests.

You can read the content using response: HttpResponse. For further information, check out the receiving content using HttpResponse section.

val call ="") {
    method = HttpMethod.Get

The request method

In addition to call, there is a request method for performing a typed request, receiving a specific type like String, HttpResponse, or an arbitrary class. You have to specify the URL and the method when building the request.

val call = client.request<String> {
    method = HttpMethod.Get

The get, post, put and delete methods

Similar to request, there are several extension methods to perform requests with the most common HTTP verbs: GET, POST, PUT and DELETE.

PATCH, HEAD and OPTIONS have special HTTP semantics, and they do not have shortcut methods, though you can use the request and call methods to perform requests with those verbs.

val text =<String>("")

When calling request methods, you can provide a lambda to build the request parameters like the URL, the HTTP method (verb), the body, or the headers. The HttpRequestBuilder looks like this:

class HttpRequestBuilder : HttpMessageBuilder {
    val url: URLBuilder
    var method: HttpMethod
    val headers: HeadersBuilder
    var body: Any = EmptyContent
    val executionContext: CompletableDeferred<Unit>
    fun header(key: String, value: String)
    fun headers(block: HeadersBuilder.() -> Unit)
    fun url(block: URLBuilder.(URLBuilder) -> Unit)

The HttpClient class only offers some basic functionality, and all the methods for building requests are exposed as extensions.
You can check the standard available HttpClient build extension methods.

The submitForm and submitFormWithBinaryData methods

There are a couple of convenience extension methods for submitting form information.

The submitForm method:

submitForm(formData: Parameters = Parameters.Empty, encodeInQuery: Boolean = false, block: HttpRequestBuilder.() -> Unit = {})

It allows to do a request with the Parameters encoded in the querystring (GET by default), or to do a request with the Parameters encoded as multipart (POST by default) depending on the encodeInQuery parameter.

The submitFormWithBinaryData method:

submitFormWithBinaryData(formData: List<PartData>, block: HttpRequestBuilder.() -> Unit = {}): T

It allows to generate a multipart POST request from a list of PartData. PartData can be PartData.FormItem, PartData.BinaryItem or PartData.FileItem.

To build a list of PartData, you can use the formData builder:

val data: List<PartData> = formData {
    // Can append: String, Number, ByteArray and Input.
    append("hello", "world")
    append("number", 10)
    append("ba", byteArrayOf(1, 2, 3, 4))
    append("input", inputStream.asInput())
    // Allow to set headers to the part:
    append("hello", "world", headersOf("X-My-Header" to "MyValue"))

Specifying custom headers

When building requests with HttpRequestBuilder, you can set custom headers. There is a final property val headers: HeadersBuilder that inherits from StringValuesBuilder. You can add or remove headers using it, or with the header convenience methods.

// this : HttpMessageBuilder

// Convenience method to add a header
header("My-Custom-Header", "HeaderValue")

// Calls methods from the headers: HeadersBuilder to manipulate the headers
headers.append("My-Custom-Header", "HeaderValue")
headers.appendAll("My-Custom-Header", listOf("HeaderValue1", "HeaderValue2"))

// Applies the headers with the `headers` convenience method
headers { // this: HeadersBuilder
    append("My-Custom-Header", "HeaderValue")
    appendAll("My-Custom-Header", listOf("HeaderValue1", "HeaderValue2"))

Specifying a body for requests

For POST and PUT requests, you can set the body property:<Unit> {
    body = // ...

The HttpRequestBuilder.body property can be a subtype of OutgoingContent as well as a String instance:

  • body = "HELLO WORLD!"
  • body = TextContent("HELLO WORLD!", ContentType.Text.Plain)
  • body = ByteArrayContent("HELLO WORLD!".toByteArray(Charsets.UTF_8))
  • body = LocalFileContent(File("build.gradle"))
  • body = JarFileContent(File("myjar.jar"), "test.txt", ContentType.fromFileExtension("txt").first())
  • body = URIFileContent(URL(""))

If you install the JsonFeature, and set the content type to application/json you can use arbitrary instances as the body, and they will be serialized as JSON:

data class HelloWorld(val hello: String)

val client = HttpClient(Apache) {
    install(JsonFeature) {
        serializer = GsonSerializer {
            // Configurable .GsonBuilder
}<Unit> {
    contentType(ContentType.Application.Json) // Required
    body = HelloWorld(hello = "world")

Remember that your classes must be top-level to be recognized by Gson.
If you try to send a class that is inside a function, the feature will send a null.

Uploading multipart/form-data

Starting with 0.9.4, Ktor HTTP Client has support for making MultiPart requests. The idea is to use the MultiPartFormDataContent(parts: List<PartData>) as OutgoingContent for the body of the request.

The easiest way is to use the submitFormWithBinaryData method.

Alternatively you can set the body directly:

val request = client.request {
    method = HttpMethod.Post
    body = FormDataContent(formData {
        append("key", "value")