Home > database >  Unresolved reference: OkHttp in ktor
Unresolved reference: OkHttp in ktor

Time:04-14

I am adding OkHttp in HttpClient. But I am getting error. Unresolved reference: OkHttp. I tried to add library in commonMain of build.gradle.kts, but I think I am missing some steps or doing something wrong. I want to use ktor Http but getting weird issue on my side. Can someone guide me, what am I am missing in my code?

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
    }
}

enter image description here

CodePudding user response:

Since OkHttp is designed to work on JVM and Android, you can't use it in the common code. You can create a different engine for each platform and inject it into the common code.

Or you can use expect-actual, see: https://ktor.io/docs/http-client-engines.html#mpp-config. You create an expect fun createHttpClient(): HttpClient in the common code, and actual fun createHttpClient(): HttpClient with the implementation for corresponding platform in each of the platform modules.

  • Related