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

相关推荐
叫我阿柒啊2 分钟前
从Java全栈到前端框架的实战之路
java·数据库·微服务·typescript·前端框架·vue3·springboot
2501_915106325 分钟前
App Store 软件上架全流程详解,iOS 应用发布步骤、uni-app 打包上传与审核要点完整指南
android·ios·小程序·https·uni-app·iphone·webview
蒋星熠12 分钟前
WebSocket网络编程深度实践:从协议原理到生产级应用
网络·数据库·redis·python·websocket·网络协议·微服务
wanhengidc1 小时前
高性价比云手机挑选指南
运维·网络·安全·游戏·智能手机
时序数据说1 小时前
物联网时序数据管理的利器:为何IoTDB备受青睐?
大数据·数据库·物联网·时序数据库·iotdb
大菠萝爱上小西瓜2 小时前
分享一篇关于雷电模拟器基于安卓9的安装环境及抓包的详细教程
android
dreams_dream2 小时前
标准 HTTP 状态码详解
网络·网络协议·http
GBASE2 小时前
GBASE南大通用技术分享:GBase 8a集群内存管理之堆内存
数据库
用户2018792831672 小时前
浅析:Synchronized的锁升级机制
android