Skip to content

從 1.6.x 遷移至 2.0.x ​

本指南提供了如何將您的 Ktor 應用程式從 1.6.x 版本遷移至 2.0.x 的說明。

Ktor 伺服器 ​

伺服器程式碼已移至 'io.ktor.server.*' 套件 ​

為了統一並更好地將伺服器與用戶端 API 區隔開來,伺服器程式碼已移至 io.ktor.server.* 套件(KTOR-2865)。 這意味著您需要更新應用程式中的相依性以及匯入,如下所示。

相依性 ​

子系統1.6.x2.0.0
Locationsio.ktor:ktor-locationsio.ktor:ktor-server-locations
Webjarsio.ktor:ktor-webjarsio.ktor:ktor-server-webjars
AutoHeadResponseio.ktor:ktor-server-coreio.ktor:ktor-server-auto-head-response
StatusPagesio.ktor:ktor-server-coreio.ktor:ktor-server-status-pages
CallIdio.ktor:ktor-server-coreio.ktor:ktor-server-call-id
DoubleReceiveio.ktor:ktor-server-coreio.ktor:ktor-server-double-receive
HTML DSLio.ktor:ktor-html-builderio.ktor:ktor-server-html-builder
FreeMarkerio.ktor:ktor-freemarkerio.ktor:ktor-server-freemarker
Velocityio.ktor:ktor-velocityio.ktor:ktor-server-velocity
Mustacheio.ktor:ktor-mustacheio.ktor:ktor-server-mustache
Thymeleafio.ktor:ktor-thymeleafio.ktor:ktor-server-thymeleaf
Pebbleio.ktor:ktor-pebbleio.ktor:ktor-server-pebble
kotlinx.serializationio.ktor:ktor-serializationio.ktor:ktor-server-content-negotiation, io.ktor:ktor-serialization-kotlinx-json
Gsonio.ktor:ktor-gsonio.ktor:ktor-server-content-negotiation, io.ktor:ktor-serialization-gson
Jacksonio.ktor:ktor-jacksonio.ktor:ktor-server-content-negotiation, io.ktor:ktor-serialization-jackson
Authenticationio.ktor:ktor-authio.ktor:ktor-server-auth
JWT authenticationio.ktor:ktor-auth-jwtio.ktor:ktor-server-auth-jwt
LDAP authenticationio.ktor:ktor-auth-ldapio.ktor:ktor-server-auth-ldap
DataConversionio.ktor:ktor-server-coreio.ktor:ktor-server-data-conversion
DefaultHeadersio.ktor:ktor-server-coreio.ktor:ktor-server-default-headers
Compressionio.ktor:ktor-server-coreio.ktor:ktor-server-compression
CachingHeadersio.ktor:ktor-server-coreio.ktor:ktor-server-caching-headers
ConditionalHeadersio.ktor:ktor-server-coreio.ktor:ktor-server-conditional-headers
CORSio.ktor:ktor-server-coreio.ktor:ktor-server-cors
Forwarded headersio.ktor:ktor-server-coreio.ktor:ktor-server-forwarded-header
HSTSio.ktor:ktor-server-coreio.ktor:ktor-server-hsts
HttpsRedirectio.ktor:ktor-server-coreio.ktor:ktor-server-http-redirect
PartialContentio.ktor:ktor-server-coreio.ktor:ktor-server-partial-content
WebSocketsio.ktor:ktor-websocketsio.ktor:ktor-server-websockets
CallLoggingio.ktor:ktor-server-coreio.ktor:ktor-server-call-logging
Micrometer metricio.ktor:ktor-metrics-micrometerio.ktor:ktor-server-metrics-micrometer
Dropwizard metricsio.ktor:ktor-metricsio.ktor:ktor-server-metrics
Sessionsio.ktor:ktor-server-coreio.ktor:ktor-server-sessions

若要一次新增所有外掛程式,可以使用 io.ktor:ktor-server 構件。

匯入 ​

子系統1.6.x2.0.0
Applicationimport io.ktor.application.*import io.ktor.server.application.*
Configurationimport io.ktor.config.*import io.ktor.server.config.*
Routingimport io.ktor.routing.*import io.ktor.server.routing.*
AutoHeadResponseimport io.ktor.features.*import io.ktor.server.plugins.autohead.*
StatusPagesimport io.ktor.features.*import io.ktor.server.plugins.statuspages.*
CallIdimport io.ktor.features.*import io.ktor.server.plugins.callid.*
DoubleReceiveimport io.ktor.features.*import io.ktor.server.plugins.doublereceive.*
Requestsimport io.ktor.request.*import io.ktor.server.request.*
Responsesimport io.ktor.response.*import io.ktor.server.response.*
Pluginsimport io.ktor.features.*import io.ktor.server.plugins.*
Locationsimport io.ktor.locations.*import io.ktor.server.locations.*
Static contentimport io.ktor.http.content.*import io.ktor.server.http.content.*
HTML DSLimport io.ktor.html.*import io.ktor.server.html.*
FreeMarkerimport io.ktor.freemarker.*import io.ktor.server.freemarker.*
Velocityimport io.ktor.velocity.*import io.ktor.server.velocity.*
Mustacheimport io.ktor.mustache.*import io.ktor.server.mustache.*
Thymeleafimport io.ktor.thymeleaf.*import io.ktor.server.thymeleaf.*
Pebbleimport io.ktor.pebble.*import io.ktor.server.pebble.*
ContentNegotiationimport io.ktor.features.*import io.ktor.server.plugins.contentnegotiation.*
kotlinx.serializationimport io.ktor.serialization.*import io.ktor.serialization.kotlinx.json.*
Gsonimport io.ktor.gson.*import io.ktor.serialization.gson.*
Jacksonimport io.ktor.jackson.*import io.ktor.serialization.jackson.*
Authenticationimport io.ktor.auth.*import io.ktor.server.auth.*
JWT authenticationimport io.ktor.auth.jwt.*import io.ktor.server.auth.jwt.*
LDAP authenticationimport io.ktor.auth.ldap.*import io.ktor.server.auth.ldap.*
Sessionsimport io.ktor.sessions.*import io.ktor.server.sessions.*
DefaultHeadersimport io.ktor.features.*import io.ktor.server.plugins.defaultheaders.*
Compressionimport io.ktor.features.*import io.ktor.server.plugins.compression.*
CachingHeadersimport io.ktor.features.*import io.ktor.server.plugins.cachingheaders.*
ConditionalHeadersimport io.ktor.features.*import io.ktor.server.plugins.conditionalheaders.*
CORSimport io.ktor.features.*import io.ktor.server.plugins.cors.*
Forwarded headersimport io.ktor.features.*import io.ktor.server.plugins.forwardedheaders.*
HSTSimport io.ktor.features.*import io.ktor.server.plugins.hsts.*
HttpsRedirectimport io.ktor.features.*import io.ktor.server.plugins.httpsredirect.*
PartialContentimport io.ktor.features.*import io.ktor.server.plugins.partialcontent.*
WebSocketsimport io.ktor.websocket.*import io.ktor.server.websocket.*
CallLoggingimport io.ktor.features.*import io.ktor.server.plugins.callloging.*
Micrometer metricimport io.ktor.metrics.micrometer.*import io.ktor.server.metrics.micrometer.*
Dropwizard metricsimport io.ktor.metrics.dropwizard.*import io.ktor.server.metrics.dropwizard.*

WebSockets 程式碼已移至 'websockets' 套件 ​

WebSockets 程式碼已從 http-cio 移至 websockets 套件。這需要按照以下方式更新匯入:

1.6.x2.0.0
import io.ktor.http.cio.websocket.*import io.ktor.websocket.*

請注意,此變更也會影響用戶端。

Feature 重新命名為 Plugin ​

在 Ktor 2.0.0 中,Feature 已重新命名為 Plugin,以更貼切地描述攔截請求/回應管線的功能(KTOR-2326)。 這會影響整個 Ktor API,並且需要按照以下說明更新您的應用程式。

匯入 ​

安裝任何外掛程式都需要更新匯入,並且還取決於將伺服器程式碼移至 io.ktor.server.* 套件:

1.6.x2.0.0
import io.ktor.features.*import io.ktor.server.plugins.*

自訂外掛程式 ​

將 Feature 重新命名為 Plugin 為與自訂外掛程式相關的 API 帶來了以下變更:

  • ApplicationFeature 介面重新命名為 BaseApplicationPlugin。
  • Features 管線階段重新命名為 Plugins。

請注意,從 v2.0.0 開始,Ktor 提供了用於建立自訂外掛程式的新 API。一般而言,此 API 不需要理解 Ktor 內部概念(例如管線、階段等)。相反地,您可以透過各種處理常式(例如 onCall、onCallReceive、onCallRespond 等)存取處理請求和回應的不同階段。您可以從此章節了解管線階段如何對應到新 API 處理常式:管線階段對應至新 API 處理常式。

內容協商與序列化 ​

內容協商與序列化的伺服器 API 經過重構,以便在伺服器和用戶端之間重用序列化程式庫。 主要變更包括:

  • ContentNegotiation 已從 ktor-server-core 移至獨立的 ktor-server-content-negotiation 構件中。
  • 序列化程式庫已從 ktor-* 移至用戶端也同樣使用的 ktor-serialization-* 構件中。

您需要更新應用程式中的相依性與匯入,如下所示。

相依性 ​

子系統1.6.x2.0.0
ContentNegotiationio.ktor:ktor-server-coreio.ktor:ktor-server-content-negotiation
kotlinx.serializationio.ktor:ktor-serializationio.ktor:ktor-serialization-kotlinx-json
Gsonio.ktor:ktor-gsonio.ktor:ktor-serialization-gson
Jacksonio.ktor:ktor-jacksonio.ktor:ktor-serialization-jackson

匯入 ​

子系統1.6.x2.0.0
kotlinx.serializationimport io.ktor.serialization.*import io.ktor.serialization.kotlinx.json.*
Gsonimport io.ktor.gson.*import io.ktor.serialization.gson.*
Jacksonimport io.ktor.jackson.*import io.ktor.serialization.jackson.*

自訂轉換器 ​

ContentConverter 介面所公開的函式簽章已變更如下:

kotlin
interface ContentConverter {
    suspend fun convertForSend(context: PipelineContext<Any, ApplicationCall>, contentType: ContentType, value: Any): Any?
    suspend fun convertForReceive(context: PipelineContext<ApplicationReceiveRequest, ApplicationCall>): Any?
}
kotlin
interface ContentConverter {
    suspend fun serialize(contentType: ContentType, charset: Charset, typeInfo: TypeInfo, value: Any): OutgoingContent?
    suspend fun deserialize(charset: Charset, typeInfo: TypeInfo, content: ByteReadChannel): Any?
}

測試 API ​

在 v2.0.0 中,Ktor 伺服器使用了新的測試 API,解決了 KTOR-971 中說明的各種問題。主要變更包括:

  • withTestApplication/withApplication 函式已被新的 testApplication 函式取代。
  • 在 testApplication 函式內部,您需要使用現有的 Ktor 用戶端執行個體向伺服器發送請求並驗證結果。
  • 若要測試特定功能(例如 Cookie 或 WebSockets),您需要建立新的用戶端執行個體並安裝對應的外掛程式。

讓我們看看將 1.6.x 測試遷移至 2.0.0 的幾個範例:

基本伺服器測試 ​

在下方的測試中,handleRequest 函式已被 client.get 請求取代:

kotlin
@Test
fun testRootLegacyApi() {
    withTestApplication(Application::module) {
        handleRequest(HttpMethod.Get, "/").apply {
            assertEquals(HttpStatusCode.OK, response.status())
            assertEquals("Hello, world!", response.content)
        }
    }
}
kotlin
@Test
fun testRoot() = testApplication {
    val response = client.get("/")
    assertEquals(HttpStatusCode.OK, response.status)
    assertEquals("Hello, world!", response.bodyAsText())
}

x-www-form-urlencoded ​

在下方的測試中,handleRequest 函式已被 client.post 請求取代:

kotlin
@Test
fun testPostLegacyApi() = withTestApplication(Application::main) {
    with(handleRequest(HttpMethod.Post, "/signup"){
        addHeader(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded.toString())
        setBody(listOf("username" to "JetBrains", "email" to "example@jetbrains.com", "password" to "foobar", "confirmation" to "foobar").formUrlEncode())
    }) {
        assertEquals("The 'JetBrains' account is created", response.content)
    }
}
kotlin
@Test
fun testPost() = testApplication {
    val response = client.post("/signup") {
        header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded.toString())
        setBody(listOf("username" to "JetBrains", "email" to "example@jetbrains.com", "password" to "foobar", "confirmation" to "foobar").formUrlEncode())
    }
    assertEquals("The 'JetBrains' account is created", response.bodyAsText())
}

multipart/form-data ​

要在 v2.0.0 中建構 multipart/form-data,您需要將 MultiPartFormDataContent 傳遞給用戶端的 setBody 函式:

kotlin
    @Test
    fun testUploadLegacyApi() = withTestApplication(Application::main) {
        with(handleRequest(HttpMethod.Post, "/upload"){
            val boundary = "WebAppBoundary"
            val fileBytes = File("ktor_logo.png").readBytes()

            addHeader(HttpHeaders.ContentType, ContentType.MultiPart.FormData.withParameter("boundary", boundary).toString())
            setBody(boundary, listOf(
                PartData.FormItem("Ktor logo", { }, headersOf(
                    HttpHeaders.ContentDisposition,
                    ContentDisposition.Inline
                        .withParameter(ContentDisposition.Parameters.Name, "description")
                        .toString()
                )),
                PartData.FileItem({ fileBytes.inputStream().asInput() }, {}, headersOf(
                    HttpHeaders.ContentDisposition,
                    ContentDisposition.File
                        .withParameter(ContentDisposition.Parameters.Name, "image")
                        .withParameter(ContentDisposition.Parameters.FileName, "ktor_logo.png")
                        .toString()
                ))
            ))
        }) {
            assertEquals("Ktor logo is uploaded to 'uploads/ktor_logo.png'", response.content)
        }
    }
kotlin
@Test
fun testUpload() = testApplication {
    val boundary = "WebAppBoundary"
    val response = client.post("/upload") {
        setBody(
            MultiPartFormDataContent(
                formData {
                    append("description", "Ktor logo")
                    append("image", File("ktor_logo.png").readBytes(), Headers.build {
                        append(HttpHeaders.ContentType, "image/png")
                        append(HttpHeaders.ContentDisposition, "filename=\"ktor_logo.png\"")
                    })
                },
                boundary,
                ContentType.MultiPart.FormData.withParameter("boundary", boundary)
            )
        )
    }
    assertEquals("Ktor logo is uploaded to 'uploads/ktor_logo.png'", response.bodyAsText())
}

JSON 資料 ​

在 v1.6.x 中,您可以使用 kotlinx.serialization 程式庫提供的 Json.encodeToString 函式序列化 JSON 資料。 在 v2.0.0 中,您需要建立新的用戶端執行個體並安裝 ContentNegotiation 外掛程式,以允許按特定格式序列化/還原序列化內容:

kotlin
@Test
fun testPostCustomerLegacyApi() = withTestApplication(Application::main) {
    with(handleRequest(HttpMethod.Post, "/customer"){
        addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString())
        setBody(Json.encodeToString(Customer(3, "Jet", "Brains")))
    }) {
        assertEquals("Customer stored correctly", response.content)
        assertEquals(HttpStatusCode.Created, response.status())
    }
}
kotlin
@Test
fun testPostCustomer() = testApplication {
    val client = createClient {
        install(ContentNegotiation) {
            json()
        }
    }
    val response = client.post("/customer") {
        contentType(ContentType.Application.Json)
        setBody(Customer(3, "Jet", "Brains"))
    }
    assertEquals("Customer stored correctly", response.bodyAsText())
    assertEquals(HttpStatusCode.Created, response.status)
}

在測試期間保留 Cookie ​

在 v1.6.x 中,cookiesSession 用於在測試時於請求之間保留 Cookie。在 v2.0.0 中,您需要建立新的用戶端執行個體並安裝 HttpCookies 外掛程式:

kotlin
    @Test
    fun testRequestsLegacyApi() = withTestApplication(Application::main) {
        fun doRequestAndCheckResponse(path: String, expected: String) {
            handleRequest(HttpMethod.Get, path).apply {
                assertEquals(expected, response.content)
            }
        }

        cookiesSession {
            handleRequest(HttpMethod.Get, "/login") {}.apply {}
            doRequestAndCheckResponse("/user", "Session ID is 123abc. Reload count is 0.")
            doRequestAndCheckResponse("/user", "Session ID is 123abc. Reload count is 1.")
            doRequestAndCheckResponse("/user", "Session ID is 123abc. Reload count is 2.")

            handleRequest(HttpMethod.Get, "/logout").apply {}
            doRequestAndCheckResponse("/user", "Session doesn't exist or is expired.")
        }
    }
kotlin
    @Test
    fun testRequests() = testApplication {
        val client = createClient {
            install(HttpCookies)
        }

        val loginResponse = client.get("/login")
        val response1 = client.get("/user")
        assertEquals("Session ID is 123abc. Reload count is 1.", response1.bodyAsText())
        val response2 = client.get("/user")
        assertEquals("Session ID is 123abc. Reload count is 2.", response2.bodyAsText())
        val response3 = client.get("/user")
        assertEquals("Session ID is 123abc. Reload count is 3.", response3.bodyAsText())
        val logoutResponse = client.get("/logout")
        assertEquals("Session doesn't exist or is expired.", logoutResponse.bodyAsText())
    }

WebSockets ​

在舊版 API 中,handleWebSocketConversation 用於測試 WebSocket 對話。在 v2.0.0 中,您可以透過用戶端提供的 WebSockets 外掛程式來測試 WebSocket 對話:

kotlin
    @Test
    fun testConversationLegacyApi() {
        withTestApplication(Application::module) {
            handleWebSocketConversation("/echo") { incoming, outgoing ->
                val greetingText = (incoming.receive() as Frame.Text).readText()
                assertEquals("Please enter your name", greetingText)

                outgoing.send(Frame.Text("JetBrains"))
                val responseText = (incoming.receive() as Frame.Text).readText()
                assertEquals("Hi, JetBrains!", responseText)
            }
        }
    }
kotlin
    @Test
    fun testConversation() {
        testApplication {
            val client = createClient {
                install(WebSockets)
            }

            client.webSocket("/echo") {
                val greetingText = (incoming.receive() as? Frame.Text)?.readText() ?: ""
                assertEquals("Please enter your name", greetingText)

                send(Frame.Text("JetBrains"))
                val responseText = (incoming.receive() as Frame.Text).readText()
                assertEquals("Hi, JetBrains!", responseText)
            }
        }
    }

DoubleReceive ​

在 v2.0.0 中,DoubleReceive 外掛程式設定引入了 cacheRawRequest 屬性,其作用與 receiveEntireContent 相反:

  • 在 v1.6.x 中,receiveEntireContent 屬性預設設定為 false。
  • 在 v2.0.0 中,cacheRawRequest 預設設定為 true。receiveEntireContent 屬性已被移除。

轉發標頭 (Forwarded headers) ​

在 v2.0.0 中,ForwardedHeaderSupport 與 XForwardedHeaderSupport 外掛程式分別重新命名為 ForwardedHeaders 與 XForwardedHeaders。

快取標頭 (Caching headers) ​

用於定義快取選項的 options 函式現在除了 OutgoingContent 之外,還接受 ApplicationCall 作為 Lambda 引數:

kotlin
install(CachingHeaders) {
    options { outgoingContent ->
        // ...
    }
}
kotlin
install(CachingHeaders) {
    options { call, outgoingContent ->
        // ...
    }
}

條件標頭 (Conditional headers) ​

用於定義資源版本清單的 version 函式現在除了 OutgoingContent 之外,還接受 ApplicationCall 作為 Lambda 引數:

kotlin
install(ConditionalHeaders) {
    version { outgoingContent ->
        // ... 
    }
}
kotlin
install(ConditionalHeaders) {
    version { call, outgoingContent ->
        // ... 
    }
}

CORS ​

在 CORS 配置中使用的數個函式已重新命名:

  • host -> allowHost
  • header -> allowHeader
  • method -> allowMethod
kotlin
install(CORS) {
    host("0.0.0.0:5000")
    header(HttpHeaders.ContentType)
    method(HttpMethod.Options)
}
kotlin
install(CORS) {
    allowHost("0.0.0.0:5000")
    allowHeader(HttpHeaders.ContentType)
    allowMethod(HttpMethod.Options)
}

MicrometerMetrics ​

在 v1.6.x 中,baseName 屬性用於指定用於監視 HTTP 請求的 Ktor 指標基底名稱(前綴)。 預設情況下,它等於 ktor.http.server。 在 v2.0.0 中,baseName 已被 metricName 取代,其預設值為 ktor.http.server.requests。

Ktor 用戶端 ​

請求與回應 ​

在 v2.0.0 中,用於發送請求與接收回應的 API 進行了更新,使其更具一致性且更容易探索(KTOR-29)。

請求函式 ​

具有多個參數的請求函式已被棄用。例如,port 與 path 參數需要替換為 HttpRequestBuilder 所公開的 url 參數:

kotlin
client.get(port = 8080, path = "/customer/3")
kotlin
client.get { url(port = 8080, path = "/customer/3") }

HttpRequestBuilder 還允許您在請求函式的 Lambda 內部指定其他請求參數。

請求主體 ​

用於設定請求主體的 HttpRequestBuilder.body 屬性已被 HttpRequestBuilder.setBody 函式取代:

kotlin
client.post("http://localhost:8080/post") {
    body = "Body content"
}
kotlin
client.post("http://localhost:8080/post") {
    setBody("Body content")
}

回應 ​

在 v2.0.0 中,請求函式(例如 get、post、put、submitForm 等)不再接受用於接收特定型別物件的泛型引數。 現在所有請求函式均傳回一個 HttpResponse 物件,該物件公開了帶有泛型引數的 body 函式,用於接收特定型別的執行個體。 您也可以使用 bodyAsText 或 bodyAsChannel 將內容作為字串或通道接收。

kotlin
val httpResponse: HttpResponse = client.get("https://ktor.io/")
val stringBody: String = httpResponse.receive()
val byteArrayBody: ByteArray = httpResponse.receive()
kotlin
val httpResponse: HttpResponse = client.get("https://ktor.io/")
val stringBody: String = httpResponse.body()
val byteArrayBody: ByteArray = httpResponse.body()

安裝了 ContentNegotiation 外掛程式後,您可以按如下方式接收任意物件:

kotlin
val customer: Customer = client.get("http://localhost:8080/customer/3")
kotlin
val customer: Customer = client.get("http://localhost:8080/customer/3").body()

串流回應 ​

由於從請求函式中移除了泛型引數,接收串流回應需要獨立的函式。 為了實現這一點,新增了帶有 prepare 前綴的函式,例如 prepareGet 或 preparePost:

kotlin
public suspend fun HttpClient.prepareGet(builder: HttpRequestBuilder): HttpStatement
public suspend fun HttpClient.preparePost(builder: HttpRequestBuilder): HttpStatement

以下範例展示了在此情況下如何修改您的程式碼:

kotlin
client.get<HttpStatement>("https://ktor.io/").execute { httpResponse ->
    val channel: ByteReadChannel = httpResponse.receive()
    while (!channel.isClosedForRead) {
        // 讀取資料
    }
}
kotlin
client.prepareGet("https://ktor.io/").execute { httpResponse ->
    val channel: ByteReadChannel = httpResponse.body()
    while (!channel.isClosedForRead) {
        // 讀取資料
    }
}

您可以在此處找到完整範例:串流資料。

回應驗證 ​

在 v2.0.0 中,用於回應驗證的 expectSuccess 屬性預設設定為 false。 這需要對您的程式碼進行以下變更:

  • 若要啟用預設驗證並針對非 2xx 回應擲回例外,請將 expectSuccess 屬性設定為 true。
  • 如果您使用 handleResponseExceptionWithRequest 處理非 2xx 例外,您還需要明確啟用 expectSuccess。

HttpResponseValidator ​

handleResponseException 函式已被 handleResponseExceptionWithRequest 取代,後者增加了對 HttpRequest 的存取權限,以便在例外中提供額外資訊:

kotlin
HttpResponseValidator {
    handleResponseException { exception ->
        // ...
    }
}
kotlin
HttpResponseValidator {
    handleResponseExceptionWithRequest { exception, request ->
        // ...
    }
}

內容協商與序列化 ​

Ktor 用戶端現在支援內容協商,並與 Ktor 伺服器共享序列化程式庫。 主要變更包括:

  • JsonFeature 已被棄用,改用 ContentNegotiation,它可以在 ktor-client-content-negotiation 構件中找到。
  • 序列化程式庫已從 ktor-client-* 移至 ktor-serialization-* 構件。

您需要更新用戶端程式碼中的相依性與匯入,如下所示。

相依性 ​

子系統1.6.x2.0.0
ContentNegotiationn/aio.ktor:ktor-client-content-negotiation
kotlinx.serializationio.ktor:ktor-client-serializationio.ktor:ktor-serialization-kotlinx-json
Gsonio.ktor:ktor-client-gsonio.ktor:ktor-serialization-gson
Jacksonio.ktor:ktor-client-jacksonio.ktor:ktor-serialization-jackson

匯入 ​

子系統1.6.x2.0.0
ContentNegotiationn/aimport io.ktor.client.plugins.contentnegotiation.*
kotlinx.serializationimport io.ktor.client.features.json.*import io.ktor.serialization.kotlinx.json.*
Gsonimport io.ktor.client.features.json.*import io.ktor.serialization.gson.*
Jacksonimport io.ktor.client.features.json.*import io.ktor.serialization.jackson.*

Bearer 認證 ​

refreshTokens 函式現在使用 RefreshTokenParams 執行個體作為 Lambda 接收者(this),而不是使用 HttpResponse Lambda 引數(it):

kotlin
bearer {
    refreshTokens {  // it: HttpResponse
        // ...
    }
}
kotlin
bearer {
    refreshTokens { // this: RefreshTokenParams
        // ...
    }
}

RefreshTokenParams 公開了以下屬性:

  • response 用於存取回應參數;
  • client 用於發送請求以重新整理權杖;
  • oldTokens 用於存取使用 loadTokens 取得的權杖。

HttpSend ​

HttpSend 外掛程式的 API 已變更如下:

kotlin
client[HttpSend].intercept { originalCall, request ->
    if (originalCall.something()) {
        val newCall = execute(request)
        // ...
    }
}
kotlin
client.plugin(HttpSend).intercept { request ->
    val originalCall = execute(request)
    if (originalCall.something()) {
        val newCall = execute(request)
        // ...
    }
}

請注意,在 v2.0.0 中,已無法使用索引存取方式來存取外掛程式。請改用 HttpClient.plugin 函式。

HttpClient.get(plugin: HttpClientPlugin) 函式已移除 ​

在 2.0.0 版本中,接受用戶端外掛程式作為參數的 HttpClient.get 函式已被移除。請改用 HttpClient.plugin 函式。

kotlin
client.get(HttpSend).intercept { ... }
// 或
client[HttpSend].intercept { ... }
kotlin
client.plugin(HttpSend).intercept { ... }

Feature 重新命名為 Plugin ​

與 Ktor 伺服器相同,用戶端 API 中的 Feature 也已重新命名為 Plugin。 這可能會影響您的應用程式,具體說明如下。

匯入 ​

更新用於安裝外掛程式的匯入:

子系統1.6.x2.0.0
  • 預設請求DefaultRequest 外掛程式可讓您為所有請求設定預設參數。
  • User agentUserAgent 外掛程式可將 User-Agent 標頭新增至所有 請求。
  • 字元集此外掛程式可讓您處理請求與回應中的純文字內容:使用已註冊的字元集填入 Accept 標頭,並根據 ContentType 字元集對請求內文進行編碼以及對回應內文進行解碼。
  • 回應驗證了解如何根據狀態碼驗證回應。
  • 逾時程式碼範例: client-timeout
  • HttpCacheHttpCache 外掛程式可讓您將先前擷取的資源儲存在記憶體內部或持久化快取中。
  • HttpSend程式碼範例: client-http-send
import io.ktor.client.features.*import io.ktor.client.plugins.*
認證Auth 外掛程式可處理用戶端應用程式中的身份驗證與授權。 import io.ktor.client.features.auth.* import io.ktor.client.features.auth.providers.* import io.ktor.client.plugins.auth.* import io.ktor.client.plugins.auth.providers.*
CookieHttpCookies 外掛程式可自動處理 Cookie,並將其保存在不同呼叫之間的儲存機制中。import io.ktor.client.features.cookies.*import io.ktor.client.plugins.cookies.*
記錄必要相依性:io.ktor:ktor-client-loggingimport io.ktor.client.features.logging.*import io.ktor.client.plugins.logging.*
WebSocketsThe Websockets plugin allows you to create a multi-way communication session between a server and a client.import io.ktor.client.features.websocket.*import io.ktor.client.plugins.websocket.*
內容編碼ContentEncoding 外掛程式可讓您啟用指定的壓縮演算法(例如 'gzip' 和 'deflate')並設定其組態。import io.ktor.client.features.compression.*import io.ktor.client.plugins.compression.*

自訂外掛程式 ​

HttpClientFeature 介面已重新命名為 HttpClientPlugin。

適用於 Native 目標的新記憶體模型 ​

在 v2.0.0 中,在 Native 目標上使用 Ktor 用戶端需要啟用新的 Kotlin/Native 記憶體模型:啟用新 MM。

從 v2.2.0 開始,新的 Kotlin/Native 記憶體模型已預設啟用。

'Ios' 引擎重新命名為 'Darwin' ​

鑑於 Ios 引擎不僅以 iOS 為目標,還支援包括 macOS 或 tvOS 在內的其他作業系統,在 v2.0.0 中,它已重新命名為 Darwin。這引發了以下變更:

  • io.ktor:ktor-client-ios 構件已重新命名為 io.ktor:ktor-client-darwin。
  • 若要建立 HttpClient 執行個體,您需要傳遞 Darwin 類別作為引數。
  • IosClientEngineConfig 組態類別已重新命名為 DarwinClientEngineConfig。

若要了解如何設定 Darwin 引擎,請參閱 Darwin 一節。

WebSockets 程式碼已移至 'websockets' 套件 ​

WebSockets 程式碼已從 http-cio 移至 websockets 套件。這需要按照以下方式更新匯入:

1.6.x2.0.0
import io.ktor.http.cio.websocket.*import io.ktor.websocket.*

預設請求 ​

DefaultRequest 外掛程式使用 DefaultRequestBuilder 組態類別取代了 HttpRequestBuilder:

kotlin
val client = HttpClient(CIO) {
    defaultRequest {
        // this: HttpRequestBuilder
    }
}
kotlin
val client = HttpClient(CIO) {
    defaultRequest {
        // this: DefaultRequestBuilder
    }
}