Kotlin 网络请求小例子(Ktor)


其实还是借着 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. 最后,我们看到右上方,会有一个小小的大象图标,点击它,等待下载完成即可。
    在这里插入图片描述
  6. 如果不小心点到了×,也可以在右侧边栏点击大象图标,右键点击项目名,点击重新加载 Gradle 项目。
    在这里插入图片描述

创建 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("https://kotlinlang.org/")
        print(response)
    }
    
    可以看到打印出了HttpResponse[https://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[https://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("https://kotlinlang.org/")
        print(response.bodyAsText())
    }
    
    数据很长,这是 html,因为本文章并不是专门讲解网络请求,就大概看一眼就行。有时候网站会抽风无法访问,在你请求时可能刚好无法访问,会直接异常。我在写文章时,https://ktor.io/就抽风了,只能换成https://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.
    <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><link rel="icon" href="/assets/images/favicon.svg?v2" type="image/svg+xml"/>......
    

相关推荐

  1. Kotlin Retrofit 网络请求

    2024-06-09 13:00:04       19 阅读
  2. 【微信程序】网络请求

    2024-06-09 13:00:04       22 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-09 13:00:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-09 13:00:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-09 13:00:04       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-09 13:00:04       20 阅读

热门阅读

  1. kotlin gradle踩过的坑

    2024-06-09 13:00:04       10 阅读
  2. 关于xilinx srio ip复位问题

    2024-06-09 13:00:04       10 阅读
  3. Elasticsearch高效检索:基础查询详解

    2024-06-09 13:00:04       10 阅读
  4. MySQL入门学习-聚合和分组.计数(COUNT()函数)

    2024-06-09 13:00:04       10 阅读
  5. ch1计算机网络和因特网

    2024-06-09 13:00:04       11 阅读
  6. bpmn+vue 中文文档

    2024-06-09 13:00:04       12 阅读
  7. 大语言模型原理基础与前沿 为什么ICL有效

    2024-06-09 13:00:04       10 阅读
  8. React——组件通信方式

    2024-06-09 13:00:04       10 阅读
  9. 我对Chat-GPT4o的使用感受

    2024-06-09 13:00:04       13 阅读
  10. 【C#】延时关闭电脑、取消关闭电脑

    2024-06-09 13:00:04       10 阅读
  11. 方法调研:DDOS检测有哪些方法?

    2024-06-09 13:00:04       11 阅读
  12. Rust 编程——prost-build 使用

    2024-06-09 13:00:04       12 阅读
  13. 速盾:ddos防护与高防ip区别?

    2024-06-09 13:00:04       7 阅读
  14. 贪心算法详解

    2024-06-09 13:00:04       10 阅读