ktor-client封装使用步骤:
1.导入依赖:
设置版本号:
buildscript {
ext.ktor_version = '2.3.1'
}
添加依赖:
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.封装网络工具类:
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.进行请求:文章来源:https://www.toymoban.com/news/detail-648481.html
private suspend fun testHttpClint(){
HttpUtils().get<BaseResponse>("", mapOf("id" to "1"))
.collect{
it.flag
}
}
PS: 网络请求需要放在协程里面使用文章来源地址https://www.toymoban.com/news/detail-648481.html
到了这里,关于android—ktor-client封装使用,请求网络的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!