Kotlin 网络请求小例子(Ktor)

作者 : admin 本文共2570个字,预计阅读时间需要7分钟 发布时间: 2024-06-5 共1人阅读

文章目录

  • 导入依赖
  • 创建 Http 客户端

其实还是借着
Ktor 学一学 Kotlin 如何导入依赖,这应该是我们 Kotlin 基础专栏的最后一期了。

Ktor 是 Kotlin 官方的一个网络请求库,它具有优秀且精炼的 API,并且是跨平台的。

本教程参考自 Ktor 文档 Create a client application。

导入依赖

  1. 找到项目的build.gradle.kts文件,双击打开。
  2. 在文件中找到dependencies
    plugins {
        kotlin("jvm") version "2.0.0"
    }
    
    group = "ink.awning"
    version = "1.0-SNAPSHOT"
    
    repositories {
        mavenCentral()
    }
    
    // 我们的依赖将在此处导入
    dependencies {
        testImplementation(kotlin("test"))
    }
    
    tasks.test {
        useJUnitPlatform()
    }
    kotlin {
        jvmToolchain(21)
    }
    
  3. dependencies中添加 Ktor 的依赖
    dependencies {
        testImplementation(kotlin("test"))
        // Ktor
        implementation("io.ktor:ktor-client-core:2.3.11")
        implementation("io.ktor:ktor-client-cio:2.3.11")
    }
    
  4. 因为这其实是 Kotlin 脚本文件,我们也可以在其中写 Kotlin 代码,可以把 Ktor 版本定义为一个变量并引用它,方便以后版本更改。
    dependencies {
        testImplementation(kotlin("test"))
        // Ktor
        val ktorVersion = "2.3.11"
        implementation("io.ktor:ktor-client-core:$ktorVersion")
        implementation("io.ktor:ktor-client-cio:$ktorVersion")
    }
    
  5. 最后,我们看到右上方,会有一个小小的大象图标,点击它,等待下载完成即可。
    Kotlin 网络请求小例子(Ktor)插图
  6. 如果不小心点到了×,也可以在右侧边栏点击大象图标,右键点击项目名,点击重新加载 Gradle 项目。
    Kotlin 网络请求小例子(Ktor)插图(1)

创建 Http 客户端

  1. main函数标记为suspend可挂起函数。
    suspend fun main() {
    
    }
    
  2. 创建一个HttpClient对象:
    import io.ktor.client.*
    import io.ktor.client.engine.cio.*
    
    
    suspend fun main() {
        val httpClient = HttpClient(CIO)
    }
    
  3. 发送get请求
    import io.ktor.client.*
    import io.ktor.client.engine.cio.*
    import io.ktor.client.request.*
    
    
    suspend fun main() {
        val httpClient = HttpClient(CIO)
    
        val response: HttpResponse = httpClient.get("http://kotlinlang.org/")
        print(response)
    }
    

    可以看到打印出了HttpResponse[http://kotlinlang.org/, 200 OK],是200 OK,说明已经请求成功

    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
    HttpResponse[http://kotlinlang.org/, 200 OK]
    

    Note:可以看到在HttpResponse前还有一些其他的内容,这是日志库SLF4J的内容,它提示找不到相关类,但并不影响代码的运行。如果你看着很烦,可以在build.gradle.kts加入相关依赖解决:

    dependencies {
    	testImplementation(kotlin("test"))
    	// Ktor
    	val ktorVersion = "2.3.11"
    	implementation("io.ktor:ktor-client-core:$ktorVersion")
    	implementation("io.ktor:ktor-client-cio:$ktorVersion")
    	// slf4j
    	implementation("org.slf4j:slf4j-log4j12:2.0.13")
    }
    
  4. 获取响应文本
    我们可以使用HttpResponse.bodyAsText()方法获取返回的文本:
    import io.ktor.client.*
    import io.ktor.client.engine.cio.*
    import io.ktor.client.request.*
    import io.ktor.client.statement.*
    
    
    suspend fun main() {
        val httpClient = HttpClient(CIO)
        val response = httpClient.get("http://kotlinlang.org/")
        print(response.bodyAsText())
    }
    

    数据很长,这是 html,因为本文章并不是专门讲解网络请求,就大概看一眼就行。有时候网站会抽风无法访问,在你请求时可能刚好无法访问,会直接异常。我在写文章时,http://ktor.io/就抽风了,只能换成http://kotlinlang.org/

    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
    ......
    
本站无任何商业行为
个人在线分享 » Kotlin 网络请求小例子(Ktor)
E-->