HTTP Client Engines

预计阅读时间:5分钟

Ktor HTTP客户端具有一个公共接口,但允许指定用于处理网络请求的引擎. 不同的引擎具有不同的配置,依赖性和支持功能.

目录:

Default engine

通过在不指定引擎的情况下调用HttpClient方法,它将使用默认引擎.

val client = HttpClient()

对于JVM,默认引擎由ServiceLoader解析,第一个可用引擎按字母顺序排序. 因此,取决于所包含的工件.

对于本地引擎,在静态链接期间检测到引擎. 请在工件中提供本机引擎之一.

对于js,它使用预定义的代码.

Configuring engines

Ktor HttpClient允许您通过调用以下命令来配置每个引擎的参数:

HttpClient(MyHttpEngine) {
    engine {
        // this: MyHttpEngineConfig
    }
}

每个引擎配置都有一些可以设置的通用属性:

  • threadsCount属性是引擎要使用的建议. 如果引擎不需要如此多的线程,则可以忽略.
  • pipelining是实验性标志,用于启用HTTP流水线 .
val client = HttpClient(MyHttpEngine) {
    engine {
        threadCount = 4
        pipelining = true
    }
}

JVM

Apache

目前,Apache是​​最可配置的HTTP客户端. 它支持HTTP / 1.1和HTTP / 2. 它是唯一支持以下重定向并允许您配置超时,代理以及org.apache.httpcomponents:httpasyncclient支持的代理的服务器.

配置示例如下所示:

val client = HttpClient(Apache) {
    engine {
        /**
         * Apache embedded http redirect, default = false. Obsolete by `HttpRedirect` feature.
         * It uses the default number of redirects defined by Apache's HttpClient that is 50.
         */
        followRedirects = true

        /**
         * Timeouts.
         * Use `0` to specify infinite.
         * Negative value mean to use the system's default value.
         */

        /**
         * Max time between TCP packets - default 10 seconds.
         */
        socketTimeout = 10_000

        /**
         * Max time to establish an HTTP connection - default 10 seconds.
         */
        connectTimeout = 10_000

        /**
         * Max time for the connection manager to start a request - 20 seconds.
         */
        connectionRequestTimeout = 20_000

        customizeClient {
            // this: HttpAsyncClientBuilder
            setProxy(HttpHost("127.0.0.1", 8080))

            // Maximum number of socket connections.
            setMaxConnTotal(1000)

            // Maximum number of requests for a specific endpoint route.
            setMaxConnPerRoute(100)

            // ...
        }
        customizeRequest {
            // this: RequestConfig.Builder from Apache.
        }
    }
}
这台发动机是在类中定义io.ktor.client.engine.apache.Apache在神器io.ktor:ktor-client-apache:$ktor_version . 它包括org.apache.httpcomponents:httpasyncclient传递依赖项.
dependencies { implementation "io.ktor:ktor-client-apache:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-apache:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-apache</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

CIO

CIO(基于协程的I / O)是Ktor实施,没有其他依赖关系,并且完全异步. 目前仅支持HTTP / 1.x.

CIO提供用于配置的maxConnectionsCountendpointConfig .

配置示例如下所示:

val client = HttpClient(CIO) {
    engine {
        /**
         * Maximum number of socket connections.
         */
        maxConnectionsCount = 1000

        /**
         * Endpoint specific settings.
         */
        endpoint {
            /**
             * Maximum number of requests for a specific endpoint route.
             */
            maxConnectionsPerRoute = 100

            /**
             * Max size of scheduled requests per connection(pipeline queue size).
             */
            pipelineMaxSize = 20

            /**
             * Max number of milliseconds to keep iddle connection alive.
             */
            keepAliveTime = 5000

            /**
             * Number of milliseconds to wait trying to connect to the server.
             */
            connectTimeout = 5000

            /**
             * Maximum number of attempts for retrying a connection.
             */
            connectRetryAttempts = 5
        }

        /**
         * Https specific settings.
         */
        https {
            /**
            * Custom server name for TLS server name extension.
             * See also: https://en.wikipedia.org/wiki/Server_Name_Indication
             */
            serverName = "api.ktor.io"

            /**
             * List of allowed [CipherSuite]s.
             */
            cipherSuites = CIOCipherSuites.SupportedSuites

            /**
             * Custom [X509TrustManager] to verify server authority.
             *
             * Use system by default.
             */
            trustManager = myCustomTrustManager

            /**
             * [SecureRandom] to use in encryption.
             */
            random = mySecureRandom
        }
    }
}
这台发动机是在类中定义io.ktor.client.engine.cio.CIO在神器io.ktor:ktor-client-cio:$ktor_version .
dependencies { implementation "io.ktor:ktor-client-cio:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-cio:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-cio</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Jetty

Jetty提供了一个额外的sslContextFactory进行配置. 目前仅支持HTTP / 2.

配置示例如下所示:

val client = HttpClient(Jetty) {
    engine {
        sslContextFactory = SslContextFactory()
    }
}
这台发动机是在类中定义io.ktor.client.engine.jetty.Jetty在神器io.ktor:ktor-client-jetty:$ktor_version . 它包括org.eclipse.jetty.http2:http2-client传递依赖项.
dependencies { implementation "io.ktor:ktor-client-jetty:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-jetty:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-jetty</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

JVM and Android

OkHttp

有一个基于OkHttp的引擎:

val client = HttpClient(OkHttp) {
    engine {
        // https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.Builder.html
        config { // this: OkHttpClient.Builder ->
            // ...
            followRedirects(true)
            // ...
        }

        // https://square.github.io/okhttp/3.x/okhttp/okhttp3/Interceptor.html
        addInterceptor(interceptor)
        addNetworkInterceptor(interceptor)

        /**
         * Set okhttp client instance to use instead of creating one.
         */
        preconfigured = okHttpClientInstance
    }

}
这台发动机是在类中定义io.ktor.client.engine.okhttp.OkHttp在神器io.ktor:ktor-client-okhttp:$ktor_version . 它包括com.squareup.okhttp3:okhttp传递依赖项.
dependencies { implementation "io.ktor:ktor-client-okhttp:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-okhttp:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-okhttp</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Android

Android引擎没有其他依赖项,而是使用具有正常HttpURLConnection的ThreadPool来执行请求. 可以这样配置:

val client = HttpClient(Android) {
    engine {
        connectTimeout = 100_000
        socketTimeout = 100_000

        /**
         * Proxy address to use.
         */
        proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress("localhost", serverPort))
    }
}
This engine is defined in the class io.ktor.client.engine.android.Android in the artifact io.ktor:ktor-client-android:$ktor_version.
dependencies { implementation "io.ktor:ktor-client-android:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-android:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-android</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

iOS

iOS引擎在内部使用异步NSURLSession . 并且没有其他配置.

val client = HttpClient(Ios) {
    /**
     * Configure native NSUrlRequest.
     */
    configureRequest { // this: NSMutableURLRequest
        setAllowsCellularAccess(true)
        // ...
    }
}
这台发动机是在类中定义io.ktor.client.engine.ios.Ios在神器io.ktor:ktor-client-ios:$ktor_version .
dependencies { implementation "io.ktor:ktor-client-ios:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-ios:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-ios</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Js (JavaScript)

Js引擎在内部使用fetch API(对于node.js运行时使用node-fetch ).

Js引擎没有自定义配置.

val client = HttpClient(Js) {
}

您还可以调用JsClient()函数来获取Js引擎单例.

这台发动机是在类中定义io.ktor.client.engine.js.Js在神器io.ktor:ktor-client-js:$ktor_version .
dependencies { implementation "io.ktor:ktor-client-js:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-js:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-js</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Curl

有一个基于Curl的引擎:

val client = HttpClient(Curl)

支持的平台:linux_x64,macos_x64,mingw_x64. 请注意,要使用引擎,您必须已安装curl库,至少版本为7.63

这台发动机是在类中定义io.ktor.client.engine.curl.Curl在神器io.ktor:ktor-client-curl:$ktor_version .
dependencies { implementation "io.ktor:ktor-client-curl:$ktor_version" }
dependencies { implementation("io.ktor:ktor-client-curl:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-curl</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

MockEngine

MockEngine是用于测试的通用引擎. 另请参见MockEngine进行测试 .

by  ICOPY.SITE