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

相关推荐
茶憶21 小时前
UniApp 安卓端实现文件的生成,写入,获取文件大小以及压缩功能
android·javascript·vue.js·uni-app
2501_9159214321 小时前
uni-app 的 iOS 打包与上架流程,多工具协作
android·ios·小程序·uni-app·cocoa·iphone·webview
云和恩墨1 天前
OceanBase企业版会话级SQL跟踪实操:DBMS_MONITOR(类Oracle 10046事件)
数据库·sql·oracle·oceanbase
为什么不问问神奇的海螺呢丶1 天前
oracle 数据库巡检 sql
数据库·sql·oracle
麦麦鸡腿堡1 天前
MySQL数据库操作指令
数据库·mysql
Lei活在当下1 天前
【Perfetto从入门到精通】4.使用 heapprofd 工具采样追踪 Java/Native 内存分配
android·性能优化·架构
陈天伟教授1 天前
人工智能训练师认证教程(2)Python os入门教程
前端·数据库·python
alexhilton1 天前
学会在Jetpack Compose中加载Lottie动画资源
android·kotlin·android jetpack
Elastic 中国社区官方博客1 天前
Elasticsearch:在分析过程中对数字进行标准化
大数据·数据库·elasticsearch·搜索引擎·全文检索
聪明努力的积极向上1 天前
【MYSQL】字符串拼接和参数化sql语句区别
数据库·sql·mysql