android—ktor-client封装使用,请求网络

ktor-client封装使用步骤:

1.导入依赖:

设置版本号:

java 复制代码
buildscript {
    ext.ktor_version = '2.3.1'
}

添加依赖:

java 复制代码
    implementation "io.ktor:ktor-client-okhttp:$ktor_version"
    implementation "io.ktor:ktor-client-auth:$ktor_version"
    implementation "io.ktor:ktor-client-core:$ktor_version"
    implementation "io.ktor:ktor-client-logging:$ktor_version"
    implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor_version")
    implementation("io.ktor:ktor-client-cio:$ktor_version")
    implementation("io.ktor:ktor-client-content-negotiation:$ktor_version")

2.封装网络工具类:

java 复制代码
class HttpUtils {
    var baseUrl = "https://test.demo.cn"
    val httpClient = HttpClient(OkHttp) {
        install(ContentNegotiation) {
            json(Json {
                prettyPrint = true
                isLenient = true
            })
        }
        install(HttpTimeout) {
            requestTimeoutMillis = 5000
            connectTimeoutMillis = 5000
        }
        install(DefaultRequest) {
            url { baseUrl }
        }
    }

    fun close() {
        httpClient.close()
    }

    inline fun <reified T> get(url: String, params: Map<String, String> = emptyMap()): Flow<T> {
        return flow {
            val response = httpClient.get(url) {
                params.forEach { parameter(it.key, it.value) }
            }
            val result = response.body<T>()
            emit(result)
        }.catch { throwable: Throwable ->
            throw throwable
        }.onCompletion { cause ->
            close()
        }.flowOn(Dispatchers.IO)
    }


    inline fun <reified T> post(url: String, params: Map<String, String> = emptyMap()): Flow<T> {
        return flow {
            val response = httpClient.post(url) {
                params.forEach { parameter(it.key, it.value) }
            }
            val result = response.body<T>()
            emit(result)
        }.catch { throwable: Throwable ->
            throw throwable
        }.onCompletion { cause ->
            close()
        }.flowOn(Dispatchers.IO)
    }


}

3.进行请求:

java 复制代码
 private suspend fun testHttpClint(){
        HttpUtils().get<BaseResponse>("", mapOf("id" to "1"))
            .collect{
                it.flag
            }
    }

PS: 网络请求需要放在协程里面使用

相关推荐
NineData7 小时前
NineData 迁移评估功能正式上线
数据库·dba
火柴就是我12 小时前
让我们实现一个更好看的内部阴影按钮
android·flutter
NineData12 小时前
数据库迁移总踩坑?用 NineData 迁移评估,提前识别所有兼容性风险
数据库·程序员·云计算
赵渝强老师14 小时前
【赵渝强老师】PostgreSQL中表的碎片
数据库·postgresql
砖厂小工18 小时前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
全栈老石18 小时前
拆解低代码引擎核心:元数据驱动的"万能表"架构
数据库·低代码
张拭心19 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心19 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
Kapaseker21 小时前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴1 天前
Android17 为什么重写 MessageQueue
android