You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin新手实现Ktor客户端类型安全请求报错,求解决方法

问题解决:Ktor类型安全请求调用报错

你的代码存在两个关键问题导致了该错误,以下是具体的解决步骤:

1. 缺少Resources扩展函数的导入

你没有导入Ktor Resources插件提供的get扩展函数,这个函数是让HttpClient能够识别并接受@Resource注解类实例的核心。需要添加以下导入语句:

import io.ktor.client.plugins.resources.get

2. 挂起函数必须在挂起上下文调用

client.get(Hoge())是挂起函数,Ktor客户端的所有请求API都属于挂起函数范畴,无法在普通非挂起函数中直接调用。你需要将hoge()声明为suspend fun,并且在协程上下文(比如runBlocking、launch等)中调用它。

修正后的完整代码

import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.resources.Resources
import io.ktor.client.plugins.resources.get
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.resources.*
import kotlinx.coroutines.runBlocking

@Resource("/")
class Hoge

class Client {

    private val client = HttpClient(CIO) {
        install(Resources)
        defaultRequest {
            host = "10.0.2.2"
            port = 8000
            url {
                protocol = URLProtocol.HTTP
            }
        }
    }

    // 修改为挂起函数
    public suspend fun hoge(): String {
        val res = client.get(Hoge())
        return res.bodyAsText()
    }
}

// 示例:在协程中调用挂起函数
fun main() = runBlocking {
    val client = Client()
    val result = client.hoge()
    println(result)
}

额外说明(针对旧版本Ktor)

如果你使用的是Ktor 1.x版本,Resources属于实验性特性,需要添加@OptIn注解来启用:

import io.ktor.util.KtorExperimentalResourcesApi

@OptIn(KtorExperimentalResourcesApi::class)
@Resource("/")
class Hoge

内容的提问来源于stack exchange,提问作者musako

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 02:35:25