下面是我尝试过的代码。我正在 commonMain 块中尝试以下代码。
suspend fun callHttpFunction(){
val clientEngine = HttpClient{
engine {
pipelining = true
threadsCount = 4
}
}
clientEngine.post<String>("https","m2.testing.com",8080,
"/TokenServiceEncrypt/api/base/TokenUpdated",requestBlock
) {
headers.append("Content-Type", "application/json")
headers.append("Accept", "application/json")
headers.append("SessionToken", "seesfssfsf")
}
clientEngine.close()
}
//HttpClient(Apache) fails and so does HttpClient(OkHttp)
最佳答案
我设法使用返回 HttpClient
的期望/实际类,并且每个平台都使用其专用的 engine 。
expect class HttpClientProvider() {
fun getHttpClient(host: String, sslPin: String): HttpClient
}
actual class HttpClientProvider {
actual fun getHttpClient(host: String, sslPin: String): HttpClient {
val okHttpClient = OkHttpClient.Builder().apply {
certificatePinner(
CertificatePinner.Builder()
.add(host, sslPin)
.build()
)
}.build()
return HttpClient(OkHttp) {
engine {
preconfigured = okHttpClient
}
}
}
}
如您所见,您可以将
OkHttpClient
传递给 preconfigured
,在那里,您可以使用 OkHttp 的所有功能(我使用 certificatePinner()
、 socketFactory()
和 sslSocketFactory
)。这也适用于 iOS(还没有时间测试)。
private val client = HttpClientProvider().getHttpClient(stage.host, stage.sslPin).config {
requestTimeout?.let {
install(HttpTimeout) {
requestTimeoutMillis = it.toLongMilliseconds()
}
}
logLevel?.let {
install(Logging) {
logger = Logger.SIMPLE
level = it
}
}
}
你也可以使用普通的
config { }
-block。关于kotlin - 如何为 KTOR HTTPclient Multiplatform Kotlin 项目配置引擎?还需要添加 SSL 证书,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59229189/