未解决的参考:ktor 中的 OkHttp

Unresolved reference: OkHttp in ktor

我正在 HttpClient 中添加 OkHttp。但我收到错误。 Unresolved reference: OkHttp。我试图在 build.gradle.ktscommonMain 中添加库,但我认为我缺少一些步骤或做错了什么。我想使用 ktor Http 但我这边遇到了奇怪的问题。有人可以指导我吗,我的代码中缺少什么?

import io.ktor.client.*
import io.ktor.client.engine.*
import io.ktor.client.engine.okhttp.*

fun createHttpClient() {
    val client = HttpClient(OkHttp)
}

build.gradle.kts

plugins {
    kotlin("multiplatform")
    kotlin("native.cocoapods")
    id("com.android.library")
}

version = "1.0"

kotlin {
    android()
    iosX64()
    iosArm64()
    iosSimulatorArm64()

    cocoapods {
        summary = "Some description for the Shared Module"
        homepage = "Link to the Shared Module homepage"
        ios.deploymentTarget = "14.1"
        framework {
            baseName = "kotlinmultiplatformsharedmodule"
        }
    }
    
    sourceSets {
        val commonMain by getting{
            dependencies {
                implementation("io.ktor:ktor-client-okhttp:2.0.0")
                implementation("io.ktor:ktor-client-core:2.0.0")
                implementation("io.insert-koin:koin-core:3.2.0-beta-1")
            }
        }
        val commonTest by getting {
            dependencies {
                implementation(kotlin("test"))
            }
        }
        val androidMain by getting
        val androidTest by getting
        val iosX64Main by getting
        val iosArm64Main by getting
        val iosSimulatorArm64Main by getting
        val iosMain by creating {
            dependsOn(commonMain)
            iosX64Main.dependsOn(this)
            iosArm64Main.dependsOn(this)
            iosSimulatorArm64Main.dependsOn(this)
        }
        val iosX64Test by getting
        val iosArm64Test by getting
        val iosSimulatorArm64Test by getting
        val iosTest by creating {
            dependsOn(commonTest)
            iosX64Test.dependsOn(this)
            iosArm64Test.dependsOn(this)
            iosSimulatorArm64Test.dependsOn(this)
        }
    }
}

android {
    compileSdk = 32
    sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
    defaultConfig {
        minSdk = 21
        targetSdk = 32
    }
}

由于 OkHttp 是为在 JVM and Android 上工作而设计的,因此您不能在公共代码中使用它。您可以为每个平台创建不同的引擎并将其注入通用代码。

或者您可以使用 expect-actual,参见:https://ktor.io/docs/http-client-engines.html#mpp-config。您在公共代码中创建一个 expect fun createHttpClient(): HttpClient,并在每个平台模块中创建相应平台的 actual fun createHttpClient(): HttpClient