遇到一个项目用Retrofit写很难受,但又不想用一些维护一阵子可能就停手的项目,所以就找到了这个框架
implementation "io.ktor:ktor-client-okhttp:1.5.3"
implementation "io.ktor:ktor-client-android:1.5.3"
implementation "io.ktor:ktor-client-logging:1.5.3"
implementation "io.ktor:ktor-client-gson:1.5.3"
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
import android.util.Log
import io.ktor.client.*
import io.ktor.client.engine.android.*
import io.ktor.client.features.json.*
import io.ktor.client.features.logging.*
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
object AraGo {
public var host: String = "localhost"
val client = HttpClient(Android) {
install(Logging) {
logger = object : Logger {
override fun log(message: String) {
Log.d("AraGo", message)
}
}
level = LogLevel.ALL
}
install(JsonFeature) {
serializer = GsonSerializer()
acceptContentTypes = acceptContentTypes + ContentType.Text.Html
}
engine {
connectTimeout = 100_000
socketTimeout = 100_000
}
}
suspend inline fun <reified T> post(
path: String,
crossinline block: HttpRequestBuilder.() -> Unit = {}
): Flow<T> {
return flow<T> {
client.post<T>(host = host, path = path) {
apply(block)
}.let {
emit(it)
}
}
}
}
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.LogUtils
import com.sw.smartmattress.base.net.AraGo
import io.ktor.client.request.forms.*
import io.ktor.http.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
AraGo.host = "脱敏处理"
TestLogin()
}
// /**
// * 登录
// */
// @FormUrlEncoded
// @POST("/LoginQuery")
// Call<LoginQuery> loginQuery(@Field("UserNm") String userNm,
// @Field("PassWord") String passWord);
fun TestLogin() {
lifecycleScope.launch(Dispatchers.IO) {
AraGo.post<LoginQuery>("脱敏处理") {
body = FormDataContent(Parameters.build {
append("脱敏处理", "脱敏处理")
append("脱敏处理", "脱敏处理")
})
}.catch {
LogUtils.eTag("AraGo",it)
}.collect {
LogUtils.dTag("AraGo",it)
}
}
}
}
是不是很简单。暂时就写这一点,等后面挖坑踩坑完再更新。