使用Ktor进行HTTP请求

Ktor是什么?


Ktor 这是一个 Kotlin 官方打造的 Web 框架,除了提供 HTTP 服务外,Ktor 还为和客户端提供了配套的库,用来进行 HTTP 请求。当然我们已经有Retrofit等其他库完成类似功能,但是作为Kotlin亲儿子,KtorCoroutine的搭配更加天衣无缝。

接下来我们通过一个小例子学习一下Ktor在Android上的使用。

gradle


Retrofit一样,Ktor在HTTP通信、JSON解析等功能模块提供了多个可选项,我们选择使用okhttpKotlinx.Serialization

dependencies {
    implementation "io.ktor:ktor-client-core:1.3.1"
    implementation "io.ktor:ktor-client-android:1.3.1"
    implementation "io.ktor:ktor-client-okhttp:1.3.1"
    implementation "io.ktor:ktor-client-serialization-jvm:1.3.1"
}

coroutine

dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3"
}

serialization

dependencies {
        classpath 'com.android.tools.build:gradle:3.6.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
apply plugin: 'kotlinx-serialization'

dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0"
}

API


通过OpenWeather 提供的API获取天气信息


ViewModel


基于MVVM开发,ViewModel封装HTTP请求,将返回的数据通过LiveData通知到UI

HttpClient

基于Okhttp创建一个HttpClient ,整个代码非常DSL

private val httpClient = HttpClient(OkHttp) {
        install(JsonFeature) {
            serializer = KotlinxSerializer(
                Json(
                    JsonConfiguration.Stable.copy()
                )
            )
        }
    }

通过httpClient就可以进行http请求了。

LiveData

viewModelScope.launch 开启协程,httpClient.post进行异步请求。

 val openWeatherMapLiveData = MutableLiveData<OpenWeatherMapJson>()

    fun getOpenWeatherMapJson() {
        viewModelScope.launch {
            try {
                val openWeatherMapJson = httpClient.post<OpenWeatherMapJson>("https://api.openweathermap.org/data/2.5/weather?q=yokohama&appid={KEY}") {
                    contentType(ContentType.Application.Json)
                }
                openWeatherMapLiveData.postValue(openWeatherMapJson)
            } catch (e:Exception) {
                Log.e("w", e.message)
            }
        }
    }

Model


JSON解析后得到以下data class

@Serializable
data class OpenWeatherMapJson(
    val coord: Coord,
    val weather: List<Weather>,
    val base: String,
    val main: Main,
    val visibility: Int,
    val wind: Wind,
    val clouds: Clouds,
    val dt: Int,
    val sys: Sys,
    val timezone: Int,
    val id: Int,
    val name: String,
    val cod: Int
)

View(Activity)


订阅ViewModel,获取数据后更新View

class MainActivity : AppCompatActivity() {

    private val viewModel by viewModels<MainViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        fab.setOnClickListener { view ->
            viewModel.getOpenWeatherMapJson()
        }
        viewModel.openWeatherMapLiveData.observe(this, Observer {
            textView.text = it.name
        })
    }
}

总结


虽然retrofit现在也支持Coroutine的使用,但是Ktor中使用Coroutine的成本更低,而且Ktor支持Kotlin MPP,当有跨平台需求时Ktor绝对是一个好选择。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Ktor 是 Kotlin 官方提供的一个轻量级、灵活的 Web 框架,它可以用于开发 Web 应用程序、API、微服务等。在 Kotlin for Desktop 中,我们可以使用 Ktor 构建和部署桌面应用程序的后端,以提供数据和服务。 下面是一个简单的 Kotlin for Desktop 中 Ktor使用示例: ```kotlin import io.ktor.application.* import io.ktor.response.* import io.ktor.routing.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main() { embeddedServer(Netty, port = 8080) { routing { get("/") { call.respondText("Hello, world!") } } }.start(wait = true) } ``` 这个示例创建了一个 Ktor 应用程序,监听 8080 端口,并且在访问根路径时返回 "Hello, world!" 字符串。可以在浏览器或者其他 HTTP 客户端中访问 http://localhost:8080/ 查看结果。 需要注意的是,在 Kotlin for Desktop 中使用 Ktor 可能需要添加额外的依赖项,例如: ```kotlin dependencies { implementation("io.ktor:ktor-server-netty:$ktor_version") implementation("io.ktor:ktor-server-core:$ktor_version") implementation("io.ktor:ktor-server-host-common:$ktor_version") implementation("io.ktor:ktor-serialization:$ktor_version") } ``` 其中 $ktor_version 是 Ktor 的版本号,可以根据需要进行修改。另外,还需要在项目的 build.gradle 或 settings.gradle 中添加 Maven 仓库: ```kotlin repositories { mavenCentral() } ``` 通过使用 Ktor,我们可以很方便地在 Kotlin for Desktop 中构建和部署后端服务,实现应用程序的完整功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fundroid

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值