android——ktor封装

ktor封装

代码如下:

Kotlin 复制代码
object KtorClient {
//    private const val BASE_URL = "http://***.**.***.62:8002"
    private const val BASE_URL = "https://mock.***.cn"

    val client = HttpClient(CIO) {
        install(ContentNegotiation) {
            json(Json {
                prettyPrint = true
                isLenient = true
            })
        }

        install(HttpTimeout) {
            requestTimeoutMillis = 10000
        }
        install(Logging) {
            logger = Logger.DEFAULT
            level = LogLevel.NONE
        }
        install(DefaultRequest) {
            url(BASE_URL)
        }
//        install(HttpRequestRetry) {
//            maxRetries = 1
//            retryIf { request, response ->
//                response.status.value in listOf(408, 429, 500, 502, 503)
//            }
//            retryOnExceptionIf { _, exception ->
//                exception is SocketTimeoutException || exception is ConnectException || exception is UnresolvedAddressException
//            }
//            delayMillis { retry ->
//                retry * 3000L
//            }
//        }
    }

    fun close() {
        client.close()
    }

    inline fun <reified T> get(url: String, params: Map<String, String> = emptyMap()): Flow<T> {
        return flow {
            val response = client.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 = client.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)
    }
}

请求:

Kotlin 复制代码
Log.e("TAG", "111开始请求网络")
                KtorClient.get<BaseResponse<List<String>>>(
                    "m1/****/api/user",
                    hashMapOf("id" to "1")
                ).collect {
                    Log.e("TAG", "请求结果=》$it")
                }

依赖引入:

Kotlin 复制代码
/**************************/
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0' // lifecycleScope
    def ktor_version = "2.3.1"
    implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.4.1'
    //observe livedata as state
    implementation 'androidx.compose.runtime:runtime-livedata:1.2.0-alpha07'
    //google sign in
    implementation 'com.google.android.gms:play-services-auth:20.1.0'
    //ktor
    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")
    implementation "ch.qos.logback:logback-classic:1.2.10"

//    implementation("io.ktor:ktor-client-features:$ktor_version")
    /******************************/
相关推荐
xiaoduyyy7 分钟前
【Android】ToolBar,滑动菜单,悬浮按钮和可交互提示等的使用方法
android
liyy61422 分钟前
Android架构组件:MVVM模式的实战应用与数据绑定技巧
android
K1t03 小时前
Android-UI设计
android·ui
吃汉堡吃到饱4 小时前
【Android】浅析MVC与MVP
android·mvc
深海呐10 小时前
Android AlertDialog圆角背景不生效的问题
android
ljl_jiaLiang10 小时前
android10 系统定制:增加应用使用数据埋点,应用使用时长统计
android·系统定制
花花鱼11 小时前
android 删除系统原有的debug.keystore,系统运行的时候,重新生成新的debug.keystore,来完成App的运行。
android
落落落sss12 小时前
sharding-jdbc分库分表
android·java·开发语言·数据库·servlet·oracle
消失的旧时光-194314 小时前
kotlin的密封类
android·开发语言·kotlin
服装学院的IT男15 小时前
【Android 13源码分析】WindowContainer窗口层级-4-Layer树
android