0
# Ktor Client Java Engine
1
2
Ktor HTTP client engine implementation that leverages Java's built-in HTTP client introduced in Java 11. This engine provides modern HTTP capabilities including HTTP/2 support, connection pooling, and SSL/TLS handling while integrating seamlessly with Ktor's asynchronous architecture using Kotlin coroutines.
3
4
## Package Information
5
6
- **Package Name**: io.ktor:ktor-client-java-jvm
7
- **Package Type**: Maven (Kotlin/JVM)
8
- **Language**: Kotlin
9
- **Platform**: JVM (Java 11+)
10
- **Installation**:
11
```kotlin
12
// build.gradle.kts
13
implementation("io.ktor:ktor-client-java-jvm:3.2.0")
14
```
15
16
```xml
17
<!-- pom.xml -->
18
<dependency>
19
<groupId>io.ktor</groupId>
20
<artifactId>ktor-client-java-jvm</artifactId>
21
<version>3.2.0</version>
22
</dependency>
23
```
24
25
## Core Imports
26
27
```kotlin
28
import io.ktor.client.engine.java.Java
29
```
30
31
For configuration:
32
33
```kotlin
34
import io.ktor.client.engine.java.Java
35
import io.ktor.client.engine.java.JavaHttpConfig
36
```
37
38
For complete HTTP client setup:
39
40
```kotlin
41
import io.ktor.client.*
42
import io.ktor.client.engine.java.*
43
import io.ktor.client.request.*
44
import io.ktor.client.statement.*
45
```
46
47
## Basic Usage
48
49
```kotlin
50
import io.ktor.client.*
51
import io.ktor.client.engine.java.*
52
import io.ktor.client.request.*
53
import io.ktor.client.statement.*
54
import java.net.http.HttpClient
55
56
// Basic client with Java engine
57
val client = HttpClient(Java)
58
59
// Make a simple GET request
60
val response: HttpResponse = client.get("https://api.example.com/data")
61
val content: String = response.bodyAsText()
62
63
// Don't forget to close the client
64
client.close()
65
```
66
67
## Advanced Usage
68
69
```kotlin
70
import io.ktor.client.*
71
import io.ktor.client.engine.java.*
72
import java.net.http.HttpClient
73
import java.net.Proxy
74
import java.net.InetSocketAddress
75
76
// Client with engine configuration
77
val client = HttpClient(Java) {
78
engine {
79
// Set HTTP protocol version
80
protocolVersion = HttpClient.Version.HTTP_2
81
82
// Configure the underlying Java HttpClient
83
config {
84
followRedirects(HttpClient.Redirect.ALWAYS)
85
// Add other HttpClient.Builder configurations
86
}
87
}
88
89
// Configure proxy (inherited from base config)
90
proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress("proxy.example.com", 8080))
91
92
// Configure timeouts (inherited from base config)
93
install(HttpTimeout) {
94
requestTimeoutMillis = 30_000
95
connectTimeoutMillis = 10_000
96
}
97
}
98
```
99
100
## Capabilities
101
102
### Engine Factory
103
104
Main entry point for creating Java HTTP client engine instances.
105
106
```kotlin { .api }
107
/**
108
* A JVM client engine that uses the Java HTTP Client introduced in Java 11.
109
* Implements HttpClientEngineFactory<JavaHttpConfig>
110
*/
111
data object Java : HttpClientEngineFactory<JavaHttpConfig> {
112
/**
113
* Create a new Java HTTP client engine instance with configuration
114
* @param block Configuration block for JavaHttpConfig
115
* @return Configured HttpClientEngine instance
116
*/
117
override fun create(block: JavaHttpConfig.() -> Unit): HttpClientEngine
118
}
119
```
120
121
### Engine Configuration
122
123
Configuration class for customizing the Java HTTP client engine behavior.
124
125
```kotlin { .api }
126
/**
127
* Configuration class for the Java HTTP client engine
128
* Extends HttpClientEngineConfig with Java-specific options
129
*/
130
public class JavaHttpConfig : HttpClientEngineConfig() {
131
/**
132
* HTTP protocol version to use for requests
133
* Default: HttpClient.Version.HTTP_1_1
134
*/
135
public var protocolVersion: HttpClient.Version = HttpClient.Version.HTTP_1_1
136
137
/**
138
* Configure the underlying Java HttpClient using HttpClient.Builder
139
* @param block Configuration block for HttpClient.Builder
140
*/
141
public fun config(block: HttpClient.Builder.() -> Unit)
142
}
143
```
144
145
### Engine Implementation
146
147
Core engine implementation class (not intended for direct instantiation - use the `Java` factory object instead).
148
149
```kotlin { .api }
150
/**
151
* Java HTTP client engine implementation
152
* Extends HttpClientEngineBase with Java-specific HTTP handling
153
* Note: Use the Java factory object instead of direct instantiation
154
*/
155
public class JavaHttpEngine(override val config: JavaHttpConfig) : HttpClientEngineBase("ktor-java") {
156
/**
157
* Set of capabilities supported by this engine
158
* Includes: HttpTimeoutCapability, WebSocketCapability, SSECapability
159
*/
160
public override val supportedCapabilities: Set<HttpClientEngineCapability<*>> =
161
setOf(HttpTimeoutCapability, WebSocketCapability, SSECapability)
162
163
/**
164
* Execute HTTP request using Java HttpClient
165
* @param data HTTP request data
166
* @return HTTP response data
167
*/
168
override suspend fun execute(data: HttpRequestData): HttpResponseData
169
}
170
```
171
172
### Service Provider Interface
173
174
Engine container for automatic discovery through Java ServiceLoader mechanism.
175
176
```kotlin { .api }
177
/**
178
* Service provider interface implementation for engine discovery
179
* Registered in META-INF/services/io.ktor.client.HttpClientEngineContainer
180
*/
181
public class JavaHttpEngineContainer : HttpClientEngineContainer {
182
/**
183
* Reference to the Java engine factory
184
*/
185
override val factory: HttpClientEngineFactory<*> = Java
186
187
/**
188
* String representation of the engine
189
* @return "Java"
190
*/
191
override fun toString(): String = "Java"
192
}
193
```
194
195
## Types
196
197
### Ktor Framework Types
198
199
These types are provided by the Ktor framework and imported when using this engine:
200
201
```kotlin { .api }
202
// Core engine types from io.ktor.client.engine
203
interface HttpClientEngine
204
interface HttpClientEngineFactory<T : HttpClientEngineConfig>
205
abstract class HttpClientEngineConfig
206
abstract class HttpClientEngineBase(engineName: String) : HttpClientEngine
207
interface HttpClientEngineContainer
208
interface HttpClientEngineCapability<T>
209
210
// HTTP types from io.ktor.client.request and io.ktor.client.call
211
class HttpRequestData
212
class HttpResponseData
213
214
// Timeout capability from io.ktor.client.plugins
215
object HttpTimeoutCapability : HttpClientEngineCapability<HttpTimeout>
216
217
// WebSocket capability from io.ktor.client.plugins.websocket
218
object WebSocketCapability : HttpClientEngineCapability<WebSocketConfig>
219
220
// SSE capability from io.ktor.client.plugins.sse
221
object SSECapability : HttpClientEngineCapability<SSEConfig>
222
```
223
224
### Protocol Versions
225
226
```kotlin { .api }
227
// From java.net.http.HttpClient.Version
228
enum class Version {
229
HTTP_1_1, // HTTP/1.1 protocol
230
HTTP_2 // HTTP/2 protocol
231
}
232
```
233
234
### Redirect Policies
235
236
```kotlin { .api }
237
// From java.net.http.HttpClient.Redirect
238
enum class Redirect {
239
NEVER, // Never follow redirects
240
ALWAYS, // Always follow redirects
241
NORMAL // Follow redirects except from HTTPS URLs to HTTP URLs
242
}
243
```
244
245
## Supported Features
246
247
### Core HTTP Features
248
- **HTTP/1.1 and HTTP/2 support** - Configurable via `protocolVersion`
249
- **Request/Response streaming** - Efficient handling of large payloads
250
- **Connection pooling** - Automatic connection reuse managed by Java HttpClient
251
- **SSL/TLS support** - Full HTTPS support with certificate validation
252
- **Compression** - Automatic gzip/deflate decompression
253
254
### Proxy Support
255
- **HTTP proxies** - Standard HTTP proxy support
256
- **SOCKS proxies** - SOCKS4/SOCKS5 proxy support
257
- **Authentication** - Proxy authentication when configured
258
259
### Timeout Configuration
260
- **Connection timeouts** - Configurable connection establishment timeouts
261
- **Request timeouts** - Per-request timeout configuration
262
- **Infinite timeout handling** - Special handling for infinite timeout values
263
264
### WebSocket Support
265
- **WebSocket connections** - Full WebSocket protocol support
266
- **Frame handling** - Text, binary, ping, pong, and close frames
267
- **Subprotocol negotiation** - WebSocket subprotocol selection
268
- **Extension support** - WebSocket extension handling
269
270
### Server-Sent Events (SSE)
271
- **SSE connections** - Server-Sent Events protocol support
272
- **Event streaming** - Continuous event stream processing
273
- **Reconnection** - Automatic reconnection on connection loss
274
275
## Error Handling
276
277
The engine handles various error conditions and maps them to appropriate Ktor exceptions:
278
279
- **HttpConnectTimeoutException** → ConnectTimeoutException
280
- **HttpTimeoutException** → HttpRequestTimeoutException
281
- **WebSocketHandshakeException** → WebSocketException
282
- **General failures** → CancellationException with cause
283
284
## Platform Requirements
285
286
- **Java Version**: Java 11 or higher (required for java.net.http.HttpClient)
287
- **Kotlin Version**: Compatible with Ktor 3.2.0 requirements
288
- **JVM Target**: JVM bytecode compatible with Java 11+
289
290
## Thread Safety
291
292
The Java HTTP client engine is thread-safe and can handle concurrent requests. The underlying Java HttpClient manages connection pooling and thread management automatically.
293
294
## Performance Characteristics
295
296
- **Connection Pooling**: Automatic connection reuse reduces overhead
297
- **HTTP/2 Multiplexing**: Efficient request multiplexing when using HTTP/2
298
- **Streaming**: Large request/response bodies are streamed efficiently
299
- **Memory Usage**: Minimal memory overhead with proper resource management