[Day 23] 用 POST 存取第三方 API

昨天我們談到怎麼用 Ktor 以 get 來取得第三方 API 的資料,今天我們來談談如何寫入第三方 API。

POST

要寫入資料,一般我們會使用 post 這個 action:

val text = client.post<String>("http://127.0.0.1:8080/")

當然,和 get 不一樣的是,我們要把寫入的資料帶入,這樣才能讓第三方 API 有內容可以寫入。

我們可能有的資料會從 body 帶入,body 可能是 String

client.post<Unit> {
    url("http://127.0.0.1:8080/")
    body = "HELLO WORLD!"
}

也可以是 File:

client.post<Unit> {
    url("http://127.0.0.1:8080/")
    body = LocalFileContent(File("build.gradle"))
}

如果我們需要用 Json 格式,我們可以透過 Jackson 套件建立:

val json = jacksonObjectMapper()
client.post<Unit> {
    url("http://127.0.0.1:8080/")
    body = TextContent(
        json.writeValueAsString(userData), 
        contentType = ContentType.Application.Json
    )
}

今天我們就談到這裡,下次我們再談其他寫入資料的方式