Default Request

This feature allows you to configure some defaults for all the requests for a specific client.

This feature is defined in the method io.ktor.client.features.defaultRequest and no additional artifacts are required.

Installation

When configuring the client, there is an extension method provided by this feature to set come defaults for this client.For example, if you want to add a header to all the requests, or configure the host, port, and method or just set the path.

  1. val client = HttpClient() {
  2. defaultRequest { // this: HttpRequestBuilder ->
  3. method = HttpMethod.Head
  4. host = "127.0.0.1"
  5. port = 8080
  6. header("X-My-Header", "MyValue")
  7. }
  8. }

Example

An example showing how to the client behaves using the MockEngine:

  1. import io.ktor.client.*
  2. import io.ktor.client.engine.*
  3. import io.ktor.client.engine.mock.*
  4. import io.ktor.client.features.*
  5. import io.ktor.client.request.*
  6. import io.ktor.http.*
  7. import kotlinx.coroutines.experimental.*
  8. import kotlinx.coroutines.experimental.io.*
  9. fun main(args: Array<String>) = runBlocking {
  10. val client = HttpClient(MockEngine) {
  11. engine {
  12. // Register request handler.
  13. addHandler { request ->
  14. with(request) {
  15. val responseText = buildString{
  16. append("method=$method,")
  17. append("host=${url.host},")
  18. append("port=${url.port},")
  19. append("path=${url.fullPath},")
  20. append("headers=$headers")
  21. }
  22. val responseHeaders = headersOf("Content-Type" to listOf(ContentType.Text.Plain.toString()))
  23. respond(responseText, headers = responseHeaders)
  24. }
  25. }
  26. }
  27. // Configure default request feature.
  28. defaultRequest {
  29. method = HttpMethod.Head
  30. host = "127.0.0.1"
  31. port = 8080
  32. header("X-My-Header", "MyValue")
  33. }
  34. }
  35. val result = client.get<String> {
  36. url {
  37. encodedPath = "/demo"
  38. }
  39. }
  40. println(result)
  41. // Prints: method=HttpMethod(value=HEAD), host=127.0.0.1, port=8080, path=/demo, headers=Headers [X-My-Header=[MyValue], Accept=[*/*]]
  42. }