0
# HTTP Statement
1
2
Prepared statement functionality for reusable HTTP requests with lazy execution, response handling, and type-safe body parsing. HTTP statements provide a way to prepare requests and execute them multiple times with different execution contexts.
3
4
## Capabilities
5
6
### HttpStatement Class
7
8
Core statement class for preparing and executing HTTP requests.
9
10
```kotlin { .api }
11
/**
12
* Prepared HTTP request statement for lazy execution
13
* @param builder - Request builder configuration
14
* @param client - HTTP client for execution
15
*/
16
class HttpStatement(
17
val builder: HttpRequestBuilder,
18
val client: HttpClient
19
) {
20
/** Execute request and return response */
21
suspend fun execute(): HttpResponse
22
23
/** Execute request with response handler */
24
suspend fun <T> execute(block: suspend (response: HttpResponse) -> T): T
25
26
/** Execute request and receive typed body */
27
suspend fun <T> body(): T
28
29
/** Execute request, receive typed body, and process it */
30
suspend fun <T, R> body(block: suspend (response: T) -> R): R
31
}
32
```
33
34
**Usage Examples:**
35
36
```kotlin
37
import io.ktor.client.*
38
import io.ktor.client.statement.*
39
40
val client = HttpClient()
41
42
// Create a prepared statement
43
val statement = client.prepareGet("https://api.example.com/users")
44
45
// Execute multiple times
46
val response1 = statement.execute()
47
val response2 = statement.execute()
48
49
// Execute with handler
50
val processedData = statement.execute { response ->
51
if (response.status.isSuccess()) {
52
response.bodyAsText()
53
} else {
54
"Error: ${response.status}"
55
}
56
}
57
58
// Execute and get typed body
59
val users: List<User> = statement.body()
60
61
// Execute, get typed body, and process
62
val userCount = statement.body<List<User>> { users ->
63
users.size
64
}
65
```
66
67
### Statement Execution
68
69
Execute prepared statements with various response handling strategies.
70
71
```kotlin { .api }
72
/**
73
* Execute request and return response
74
* @return HttpResponse for manual processing
75
*/
76
suspend fun execute(): HttpResponse
77
78
/**
79
* Execute request with response handler
80
* @param block - Response processing block
81
* @return Processed result from block
82
*/
83
suspend fun <T> execute(block: suspend (response: HttpResponse) -> T): T
84
```
85
86
### Typed Body Handling
87
88
Type-safe response body parsing with optional processing.
89
90
```kotlin { .api }
91
/**
92
* Execute request and receive typed body
93
* @return Deserialized response body
94
*/
95
suspend fun <T> body(): T
96
97
/**
98
* Execute request, receive typed body, and process it
99
* @param block - Body processing block
100
* @return Processed result from block
101
*/
102
suspend fun <T, R> body(block: suspend (response: T) -> R): R
103
```
104
105
### Statement Creation
106
107
Extension functions for creating prepared statements from HTTP clients.
108
109
```kotlin { .api }
110
// Prepare request methods
111
suspend fun HttpClient.prepareRequest(
112
builder: HttpRequestBuilder
113
): HttpStatement
114
115
suspend fun HttpClient.prepareRequest(
116
block: HttpRequestBuilder.() -> Unit = {}
117
): HttpStatement
118
119
suspend fun HttpClient.prepareRequest(
120
urlString: String,
121
block: HttpRequestBuilder.() -> Unit = {}
122
): HttpStatement
123
124
// HTTP method-specific preparation
125
suspend fun HttpClient.prepareGet(urlString: String): HttpStatement
126
suspend fun HttpClient.preparePost(
127
urlString: String,
128
block: HttpRequestBuilder.() -> Unit = {}
129
): HttpStatement
130
suspend fun HttpClient.preparePut(
131
urlString: String,
132
block: HttpRequestBuilder.() -> Unit = {}
133
): HttpStatement
134
suspend fun HttpClient.prepareDelete(urlString: String): HttpStatement
135
suspend fun HttpClient.prepareHead(urlString: String): HttpStatement
136
suspend fun HttpClient.prepareOptions(urlString: String): HttpStatement
137
suspend fun HttpClient.preparePatch(
138
urlString: String,
139
block: HttpRequestBuilder.() -> Unit = {}
140
): HttpStatement
141
```
142
143
**Advanced Usage Examples:**
144
145
```kotlin
146
import io.ktor.client.*
147
import io.ktor.client.request.*
148
import io.ktor.client.statement.*
149
150
val client = HttpClient()
151
152
// Prepare POST request with body
153
val postStatement = client.preparePost("https://api.example.com/users") {
154
header("Content-Type", "application/json")
155
setBody("""{"name": "John", "email": "john@example.com"}""")
156
}
157
158
// Execute with error handling
159
val result = postStatement.execute { response ->
160
when {
161
response.status.isSuccess() -> {
162
val user: User = response.body()
163
"Created user: ${user.name}"
164
}
165
response.status.value == 409 -> {
166
"User already exists"
167
}
168
else -> {
169
"Error: ${response.status.description}"
170
}
171
}
172
}
173
174
// Reuse statement with different processing
175
val userId = postStatement.body<User> { user -> user.id }
176
val userName = postStatement.body<User> { user -> user.name }
177
```
178
179
## Benefits of HTTP Statements
180
181
- **Reusability**: Prepare once, execute multiple times
182
- **Lazy Execution**: Request is only sent when execute() is called
183
- **Type Safety**: Generic type parameters ensure type-safe response handling
184
- **Memory Efficiency**: Avoids recreating request builders for repeated requests
185
- **Error Handling**: Centralized error handling in execution blocks
186
- **Flexible Processing**: Multiple ways to handle responses based on use case