Ktor 1.6.7 Help

Making requests

After setting up the client, you can make HTTP requests. The main way for making HTTP requests is the request function that takes a URL as a parameter. Inside this function, you can configure various request parameters:

  • Specify an HTTP method, such as GET, POST, PUT, DELETE, HEAD, OPTION, or PATCH.

  • Add headers and cookies.

  • Set the body of a request, for example, a plain text, a data object, or form parameters.

These parameters are exposed by the HttpRequestBuilder class.

import io.ktor.client.request.* import io.ktor.client.statement.* val response: HttpResponse = client.request("https://ktor.io/") { // Configure request parameters exposed by [[[HttpRequestBuilder|https://api.ktor.io/ktor-client/ktor-client-core/ktor-client-core/io.ktor.client.request/-http-request-builder/index.html]]] }

Note that this function allows you to receive a response in various ways. In this example, we receive a response as an HttpResponse object.

Set request parameters

In this section, we'll see on how to specify various request parameters, including an HTTP method, headers, and cookies. If you need to configure some default parameters for all requests of a specific client, use the Default request plugin.

HTTP method

When calling the request function, you can specify the desired HTTP method using the method property:

import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* val response: HttpResponse = client.request("https://ktor.io/") { method = HttpMethod.Get }

In addition to the request function, HttpClient provides specific functions for basic HTTP methods: get, post, put, and so on. For example, you can replace the example above with the following code:

import io.ktor.client.request.* import io.ktor.client.statement.* val response: HttpResponse = client.get("https://ktor.io/")

Headers

To add headers to the request, use the headers function:

import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* val response: HttpResponse = client.get("https://ktor.io/") { headers { append(HttpHeaders.Accept, "text/html") append(HttpHeaders.Authorization, "token") append(HttpHeaders.UserAgent, "ktor client") } }

Cookies

To send cookies, use the cookie function:

import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.util.date.* val response: HttpResponse = client.get("https://ktor.io/") { cookie(name = "user_name", value = "jetbrains", expires = GMTDate( seconds = 0, minutes = 0, hours = 10, dayOfMonth = 1, month = Month.APRIL, year = 2022 )) }

Note that Ktor provides the Cookies plugin that allows you to keep cookies between calls.

Query parameters

To add query string parameters, call the parameter function:

import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* val response: HttpResponse = client.get("http://localhost:8080/products") { parameter("price", "asc") }

Set request body

To set the body of a request, you need to specify the body property via HttpRequestBuilder. This property accepts different types of payloads, including plain text, arbitrary class instances, form data, byte arrays, and so on. Below we'll take a look at several examples.

Text

Sending plain text as body can be implemented in the following way:

import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* val response: HttpResponse = client.post("http://localhost:8080/post") { body = "Body content" }

Objects

With the enabled Json plugin, you can send a class instance within a request body as JSON. To do this, assign a class instance to the body property and set the content type to application/json using the contentType function:

val response: HttpResponse = client.post("http://localhost:8080/customer") { contentType(ContentType.Application.Json) body = Customer(3, "Jet", "Brains") }

You can learn more from the Json help section.

Form parameters

The Ktor client provides the submitForm function for sending form parameters using both x-www-form-urlencoded and multipart/form-data types. In a code snippet below, this function accepts the following parameters:

  • url specifies a URL for making a request.

  • formParameters a set of form parameters built using Parameters.build.

  • encodeInQuery is used to send form data in URL parameters by using the GET request.

val response: HttpResponse = client.submitForm( url = "http://localhost:8080/get", formParameters = Parameters.build { append("first_name", "Jet") append("last_name", "Brains") }, encodeInQuery = true )

Upload a file

If you need to send a file with a form, use the submitFormWithBinaryData function. When calling this function, you need to specify the formData parameter, which can be initialized using the formData function. A runnable code example below shows how to do this:

val response: HttpResponse = client.submitFormWithBinaryData( url = "http://localhost:8080/upload", formData = formData { append("description", "Ktor logo") append("image", File("ktor_logo.png").readBytes(), Headers.build { append(HttpHeaders.ContentType, "image/png") append(HttpHeaders.ContentDisposition, "filename=ktor_logo.png") }) } ) { onUpload { bytesSentTotal, contentLength -> println("Sent $bytesSentTotal bytes from $contentLength") } }

Note that in this example the onUpload extension function is used to display upload progress:

onUpload { bytesSentTotal, contentLength -> println("Sent $bytesSentTotal bytes from $contentLength") }

Parallel requests

When sending two requests at once, the client suspends the second request execution until the first one is finished. If you need to perform several requests at once, you can use launch or async functions. The code snippet below shows how to perform two requests asynchronously:

val client = HttpClient(CIO) val firstRequest: Deferred<String> = async { client.get("http://localhost:8080/path1") } val secondRequest: Deferred<String> = async { client.get("http://localhost:8080/path2") } val firstRequestContent = firstRequest.await() val secondRequestContent = secondRequest.await()

To see a full example, go to client-parallel-requests.

Cancel a request

If you need to cancel a request, you can cancel a coroutine that runs this request. The launch function returns a Job that can be used to cancel the running coroutine:

import kotlinx.coroutines.* val client = HttpClient(CIO) val job = launch { val requestContent: String = client.get("http://localhost:8080") } job.cancel()

Learn more about Cancellation and timeouts.

Last modified: 27 September 2021