其他分享
首页 > 其他分享> > 使用 Kotlin 协程 + Retrofit2 调用 REST API

使用 Kotlin 协程 + Retrofit2 调用 REST API

作者:互联网

JSON : Placeholder

JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站。
以下使用 RxJava2 + Retrofit2 调用该网站的 REST API,获取字符串以及 JSON 数据。

所有 GET API 都返回JSON数据,格式(JSON-Schema)如下:

{
  "type":"object",
  "properties": {
    "userId": {"type" : "integer"},
    "id": {"type" : "integer"},
    "title": {"type" : "string"},
    "body": {"type" : "string"}
  }
}

创建工程

打开 Intellij IDEA,File / New / Project...
在 New Project 向导的第1页,选 Kotlin, Project Template 选 JVM Application,Build System 选 Gradle Kotlin,Project JDK 选 1.8。
在向导的第2页 Template 选 Console Application
点击 Finish 按钮创建工程

build.gradle.kts 内容如下

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    kotlin("jvm") version "1.4.32"
    application
}

group = "me.xxxx"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(kotlin("test-junit"))
}

tasks.test {
    useJUnit()
}

tasks.withType<KotlinCompile>() {
    kotlinOptions.jvmTarget = "1.8"
}

application {
    mainClassName = "MainKt"
}

将 dependencies 这部分的内容改为:

dependencies {
    testImplementation(kotlin("test-junit"))
    val retrofitVersion = "2.9.0"
    implementation("com.squareup.retrofit2:retrofit:$retrofitVersion")
    implementation("com.squareup.retrofit2:converter-gson:$retrofitVersion")
    implementation("com.squareup.retrofit2:converter-scalars:$retrofitVersion")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3-native-mt")
}

这一段引用了 Kotlin 协程和 Retrofit 这两个库。
其中 Retrofit 这个库中还包含了 Gson 和字符串的转换器。

Post 对象

jsonschema2pojo 可以将 JSON 数据或格式自动转换为 Java 的 POJO 类。

data class Post(val userId: Int, val id: Int, val title: String, val body: String) {
    override fun toString() =
        "Post {userId = $userId, id = $id, title = \"$title\", body = \"${body.replace("\n", "\\n")}\"}"
}

Post 对象负责 Kotlin 对象与 JSON 数据之间的相互转换。
由于两者字段名相同,这里不需要使用注解。

// 如果需要加上注解的话
data class Post(@SerializedName("userId") @Expose val userId: Int,
                @SerializedName("id") @Expose val id: Int,
                @SerializedName("title") @Expose val title: String,
                @SerializedName("body") @Expose val body: String) {
// ...
}

Retrofit 接口

interface RestPost {
    @GET
    suspend fun getPostAsString(@Url url: String): String
    @GET("posts/{id}")
    suspend fun getPostAsJson(@Path("id") id: Int): Post
    @GET("posts")
    suspend fun getPosts(): List<Post>
    @FormUrlEncoded
    @POST("posts")
    suspend fun createPost(@Field("userId") userId: Int,
                   @Field("title") title: String,
                   @Field("body") body: String): Post
    @FormUrlEncoded
    @PUT("posts/{id}")
    suspend fun updatePost(@Field("userId") userId: Int,
                   @Path("id") id: Int,
                   @Field("title") title: String,
                   @Field("body") body: String): Post
    @DELETE("posts/{id}")
    suspend fun deletePost(@Path("id") id: Int): String
}

Retrofit 库使用专用接口调用 REST API。

Retrofit 对象

val retrofitJson: Retrofit = Retrofit.Builder()
    .baseUrl("https://jsonplaceholder.typicode.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()
val retrofitString: Retrofit = Retrofit.Builder()
    .baseUrl("https://jsonplaceholder.typicode.com/")
    .addConverterFactory(ScalarsConverterFactory.create())
    .build()

调用 REST API

suspend fun getPostAsString(): String =
    retrofitString.create(RestPost::class.java)
        .getPostAsString("posts/1")

suspend fun getPostAsJson(): Post =
    retrofitJson.create(RestPost::class.java)
        .getPostAsJson(1)

suspend fun getPosts(n: Int): List<Post> =
    retrofitJson.create(RestPost::class.java)
        .getPosts().take(n)

suspend fun createPost(): Post =
    retrofitJson.create(RestPost::class.java)
        .createPost(101, "test title", "test body")

suspend fun updatePost(): Post =
    retrofitJson.create(RestPost::class.java)
        .updatePost(101, 1, "test title", "test body")

suspend fun deletePost(): String =
    retrofitString.create(RestPost::class.java)
        .deletePost(1)

main 函数

fun main(args: Array<String>) = runBlocking {
    println(getPostAsString())
    println(getPostAsJson())
    println(getPosts(2))
    println(createPost())
    println(updatePost())
    println(deletePost())
}

输出结果

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Post {userId = 1, id = 1, title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body = "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
[Post {userId = 1, id = 1, title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body = "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}, Post {userId = 1, id = 2, title = "qui est esse", body = "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"}]
Post {userId = 101, id = 101, title = "test title", body = "test body"}
Post {userId = 101, id = 1, title = "test title", body = "test body"}
{}

标签:body,Retrofit2,title,Kotlin,userId,REST,fun,Post,id
来源: https://www.cnblogs.com/zwvista/p/14613060.html