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.*
10. fun main(args: Array<String>) = runBlocking {
11. val client = HttpClient(MockEngine) {
12. engine {
13. // Register request handler.
14. addHandler { request ->
15. with(request) {
16. val responseText = buildString{
17. append("method=$method,")
18. append("host=${url.host},")
19. append("port=${url.port},")
20. append("path=${url.fullPath},")
21. append("headers=$headers")
22. }
23. val responseHeaders = headersOf("Content-Type" to listOf(ContentType.Text.Plain.toString()))
25. respond(responseText, headers = responseHeaders)
26. }
27. }
28. }
30. // Configure default request feature.
31. defaultRequest {
32. method = HttpMethod.Head
33. host = "127.0.0.1"
34. port = 8080
35. header("X-My-Header", "MyValue")
36. }
37. }
39. val result = client.get<String> {
40. url {
41. encodedPath = "/demo"
42. }
43. }
45. println(result)
46. // Prints: method=HttpMethod(value=HEAD), host=127.0.0.1, port=8080, path=/demo, headers=Headers [X-My-Header=[MyValue], Accept=[*/*]]
47. }
