HTTP/2
HTTP/2 is a modern binary multiplexing protocol designed as a replacement for HTTP/1.x.
Ktor supports HTTP/2 with the Jetty and Netty server engines. However, there are significant differences, and each engine requires additional configuration. Once your host is configured, HTTP/2 support is activated automatically.
For HTTP/2 over TLS, you typically need:
An SSL certificate, which can be self-signed.
An ALPN implementation supported by the selected engine.
HTTP/2 over cleartext (h2c) is available with the Netty engine and doesn't require SSL or ALPN configuration.
Configure an SSL certificate
HTTP/2 doesn't require TLS, but browsers typically support HTTP/2 only over encrypted connections. To use HTTP/2 over TLS, you need to configure an SSL certificate for your server.
For testing, you can generate a self-signed certificate using the JDK keytool utility:
You can also create a keystore programmatically using the buildKeyStore() function.
Then, configure Ktor to use the keystore in your application.conf or application.yaml configuration file:
Configure ALPN
HTTP/2 over TLS uses Application-Layer Protocol Negotiation (ALPN) to negotiate the protocol between the client and server. ALPN configuration depends on the server engine.
Jetty
The Jetty engine handles ALPN without additional Ktor configuration. To use HTTP/2 over TLS with Jetty:
Create a server with the Jetty engine.
Configure
sslPort.
Netty
To use HTTP/2 over TLS with Netty, add the Netty tcnative OpenSSL bindings.
The following example adds the statically linked BoringSSL implementation to the build.gradle.kts file:
The tc.native.classifier can be linux-x86_64, osx-x86_64, or windows-x86_64.
HTTP/2 without TLS
The Netty engine supports HTTP/2 over cleartext (h2c), which allows HTTP/2 communication without TLS. This can be useful within private networks where encryption is not required.
Clients can connect using h2c directly or upgrade an HTTP/1.1 connection to HTTP/2.
To enable h2c, set both enableH2c and enableHttp2 options to true in the engine configuration:
You can enable h2c and HTTP/2 over TLS on the same server. Cleartext connectors accept h2c connections, while SSL connectors use HTTP/2 over TLS.