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")
    /******************************/
相关推荐
雨白7 小时前
Jetpack系列(二):Lifecycle与LiveData结合,打造响应式UI
android·android jetpack
kk爱闹8 小时前
【挑战14天学完python和pytorch】- day01
android·pytorch·python
每次的天空10 小时前
Android-自定义View的实战学习总结
android·学习·kotlin·音视频
恋猫de小郭11 小时前
Flutter Widget Preview 功能已合并到 master,提前在体验毛坯的预览支持
android·flutter·ios
断剑重铸之日12 小时前
Android自定义相机开发(类似OCR扫描相机)
android
随心最为安12 小时前
Android Library Maven 发布完整流程指南
android
岁月玲珑12 小时前
【使用Android Studio调试手机app时候手机老掉线问题】
android·ide·android studio
还鮟16 小时前
CTF Web的数组巧用
android
小蜜蜂嗡嗡17 小时前
Android Studio flutter项目运行、打包时间太长
android·flutter·android studio
aqi0017 小时前
FFmpeg开发笔记(七十一)使用国产的QPlayer2实现双播放器观看视频
android·ffmpeg·音视频·流媒体