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

相关推荐
瀚高PG实验室1 小时前
HGDB集群(安全版)repmgr手动切换主备库
java·数据库·安全·瀚高数据库
mit6.8241 小时前
[C# starter-kit] Domain Entities | `AuditableEntity`基类 | 跟踪变化 | 软删除
数据库·microsoft·c#
潇凝子潇1 小时前
MySQL Redo Log 和 Undo Log 满了会有什么问题
数据库·mysql
HaSaKing_7211 小时前
二三级等保检测对比项
linux·服务器·网络
2501_915106321 小时前
苹果软件加固与 iOS App 混淆完整指南,IPA 文件加密、无源码混淆与代码保护实战
android·ios·小程序·https·uni-app·iphone·webview
2501_915921432 小时前
iOS 26 崩溃日志解析,新版系统下崩溃获取与诊断策略
android·ios·小程序·uni-app·cocoa·iphone·策略模式
2301_793167992 小时前
网络管理部分
linux·运维·服务器·网络·php
搬砖的小码农_Sky3 小时前
Windows操作系统上`ping`命令的用法详解
运维·网络·windows
周杰伦_Jay4 小时前
【Homebrew安装 MySQL 】macOS 用 Homebrew 安装 MySQL 完整教程
数据库·mysql·macos
齊家治國平天下4 小时前
Android 14 Input 事件派发机制深度剖析
android·input·hal