HTTP/2
HTTP/2 is a modern binary duplex multiplexing protocol designed as a replacement for HTTP/1.x.
Jetty and Netty engines provide HTTP/2 implementations that Ktor can use. However, there are significant differences, and each engine requires additional configuration. Once your host is configured properly for Ktor, HTTP/2 support will be activated automatically.
Key requirements:
An SSL certificate (can be self-signed).
An ALPN implementation suitable for a particular engine (see corresponding sections for Netty and Jetty).
SSL certificate
As per the specification, HTTP/2 does not require encryption, but all browsers will require encrypted connections to be used with HTTP/2. That's why a working TLS environment is a prerequisite for enabling HTTP/2. Therefore, a certificate is required to enable encryption. For testing purposes, it can be generated with keytool
from the JDK ...
... or by using the buildKeyStore function.
The next step is configuring Ktor to use your keystore. See the example application.conf
/application.yaml
configuration files:
ALPN implementation
HTTP/2 requires ALPN (Application-Layer Protocol Negotiation) to be enabled. The first option is to use an external ALPN implementation that needs to be added to the boot classpath. Another option is to use OpenSSL native bindings and precompiled native binaries. Also, each particular engine can support only one of these methods.
Jetty
Since ALPN APIs are supported starting with Java 8, the Jetty engine doesn't require any specific configurations for using HTTP/2. So, you only need to:
Create a server with the Jetty engine.
Add an SSL configuration as described in SSL certificate.
Configure
sslPort
.
The http2-jetty runnable example demonstrates HTTP/2 support for Jetty.
Netty
To enable HTTP/2 in Netty, use OpenSSL bindings (tcnative netty port). The example below shows how to add a native implementation (statically linked BoringSSL library, a fork of OpenSSL) to the build.gradle.kts
file:
tc.native.classifier
should be one of the following: linux-x86_64
, osx-x86_64
, or windows-x86_64
. The http2-netty runnable example demonstrates how to enable HTTP/2 support for Netty.