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 = trueisLenient = true})}install(HttpTimeout) {requestTimeoutMillis = 5000connectTimeoutMillis = 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.进行请求:
private suspend fun testHttpClint(){HttpUtils().get<BaseResponse>("", mapOf("id" to "1")).collect{it.flag}}
PS: 网络请求需要放在协程里面使用