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: 网络请求需要放在协程里面使用

相关推荐
xcLeigh17 小时前
KES数据库安全、权限、审计实战
数据库·安全·备份·权限·审计·ssl加密·密码策略
一袋米扛几楼9817 小时前
【网络】网络规划与底层通信:自顶向下方法论 (Top-Down Methodology) 全解析
网络·工程
zjy2777717 小时前
c++如何实现日志文件的异步落盘功能_基于无锁队列方案【附代码】
jvm·数据库·python
河阿里17 小时前
SQL:深分页问题深度解析
数据库·sql
wang3zc17 小时前
JavaScript中函数声明位置对解析器预编译的影响
jvm·数据库·python
涤生大数据17 小时前
AI时代,SQL该何去何从?
数据库·人工智能·sql
liulilittle17 小时前
TCP BBR 拥塞控制模块编译
网络·网络协议·tcp/ip
鱼儿也有烦恼17 小时前
8 issues were found when checking AAR metadata:
android
yexuhgu18 小时前
C#怎么使用Tuple元组返回多个值_C#如何简化方法返回值【基础】
jvm·数据库·python
HalvmånEver18 小时前
MySQL的索引
android·linux·数据库·学习·mysql