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")
    /******************************/
相关推荐
-优势在我1 小时前
Android TabLayout 实现随意控制item之间的间距
android·java·ui
hedalei1 小时前
android13修改系统Launcher不跟随重力感应旋转
android·launcher
Indoraptor2 小时前
Android Fence 同步框架
android
峥嵘life3 小时前
DeepSeek本地搭建 和 Android
android
叶羽西3 小时前
Android14 Camera框架中Jpeg流buffer大小的计算
android·安卓
jiasting3 小时前
Android 中 如何监控 某个磁盘有哪些进程或线程在持续的读写
android
AnalogElectronic5 小时前
问题记录,在使用android studio 构建项目时遇到的问题
android·ide·android studio
我爱松子鱼6 小时前
mysql之InnoDB Buffer Pool 深度解析与性能优化
android·mysql·性能优化
江上清风山间明月9 小时前
Flutter开发的应用页面非常多时如何高效管理路由
android·flutter·路由·页面管理·routes·ongenerateroute
子非衣12 小时前
MySQL修改JSON格式数据示例
android·mysql·json